Cómo: Realizar una transferencia de archivos por infrarrojos

Actualización: noviembre 2007

.NET Compact Framework proporciona las clases necesarias para las comunicaciones por infrarrojos entre dispositivos. En este ejemplo se muestra la forma de enviar y recibir archivos entre dispositivos utilizando comunicaciones por infrarrojos. Se necesitan dos Pocket PC, uno para enviar al archivo y otro para recibirlo.

En este ejemplo se crea una instancia de IrDAClient y se utiliza su método DiscoverDevices para descubrir dispositivos de infrarrojos dentro de la gama. Este método devuelve una matriz de objetos IrDADeviceInfo que proporcionan información sobre cada dispositivo.

En este ejemplo se proporciona código para enviar y recibir un archivo; ello se puede ilustrar con un botón Send y Receive. Como mínimo, es necesario crear una aplicación Send para un dispositivo y una aplicación Receive para el otro dispositivo.

El botón Send envía un archivo sólo a un dispositivo que ha estado escuchando las solicitudes de envío de un archivo. Por consiguiente, se debe puntear el botón Receive en el dispositivo receptor antes de puntear el botón Send en el dispositivo emisor. Se realizan las tareas siguientes:

  • Obtener una secuencia del archivo que se va a enviar.

  • Crear una instancia de IrDAClient utilizando el nombre de servicio determinado para esta aplicación. Las conexiones por infrarrojos se realizan especificando un nombre de servicio, que puede ser cualquier valor proporcionado con el que los dispositivos participantes hacen referencia al mismo nombre. En este ejemplo, el nombre de servicio es "IrDATest".

  • Leer la secuencia del archivo en la secuencia de IrDAClient que envía el archivo.

El botón Receive crea una instancia de IrDAListener para escuchar el dispositivo con el mismo nombre de servicio que la instancia de IrDAClient en el dispositivo emisor.

Se realizan las tareas siguientes:

  • Crear una secuencia para escribir el contenido transferido en un archivo de destino de la carpeta Mis documentos.

  • Crear una instancia de IrDAEndPoint con el identificador de dispositivo y el nombre del servicio del dispositivo emisor.

  • Crear una instancia de IrDAListener a partir de la instancia de IrDAEndPoint e iniciar el servicio de escucha.

  • Crear una instancia de IrDAClient a partir de la instancia de IrDAListener utilizando el método AcceptIrDAClient.

  • Leer la secuencia subyacente de la instancia de IrDAClient que contiene los datos del archivo transferido.

  • Escribir esa secuencia de datos en la secuencia correspondiente al archivo Receive.txt.

Para crear las aplicaciones

  1. Cree una aplicación de Pocket PC para el dispositivo emisor y agregue un botón al formulario. Asigne al botón el nombre Send.

  2. Cree un archivo denominado Send.txt en la carpeta Mis documentos.

  3. Agregue el código siguiente para el evento Click del botón Send.

    ' Align the infrared ports of the devices.
    ' Click the Receive button first, then click Send.
    Private Sub SendButton_Click(sender As Object, e As System.EventArgs) _
        Handles SendButton.Click
    
        Dim irClient As New IrDAClient()
        Dim irServiceName As String = "IrDATest"
        Dim irDevices() As IrDADeviceInfo
        Dim buffersize As Integer = 256
    
        ' Create a collection of devices to discover.
        irDevices = irClient.DiscoverDevices(2)
    
        ' Show the name of the first device found.
        If irDevices.Length = 0 Then
            MessageBox.Show("No remote infrared devices found.")
            Return
        End If
    
        Try
            Dim irEndP As New IrDAEndPoint(irDevices(0).DeviceID, _
                irServiceName)
            Dim irListen As New IrDAListener(irEndP)
            irListen.Start()
            irClient = irListen.AcceptIrDAClient()
            MessageBox.Show("Connected!")
    
        Catch exSoc As SocketException
             MessageBox.Show("Couldn't listen on service " & irServiceName & ": " _
                & exSoc.ErrorCode)
        End Try
    
        ' Open a file to send and get its stream.
        Dim fs As Stream
        Try
            fs = New FileStream(".\My Documents\send.txt", FileMode.Open)
        Catch exFile As Exception
            MessageBox.Show("Cannot open " & exFile.ToString())
            Return
        End Try
    
        ' Get the underlying stream of the client.
        Dim baseStream As Stream = irClient.GetStream()
    
        ' Get the size of the file to send
        ' and write its size to the stream.
        Dim length As Byte() = BitConverter.GetBytes(fs.Length)
        baseStream.Write(length, 0, length.Length)
    
        ' Create a buffer for reading the file.
        Dim buffer(buffersize) As Byte
    
        Dim fileLength As Integer = CInt(fs.Length)
    
        Try
            ' Read the file stream into the base stream.
            While fileLength > 0
                Dim numRead As Int64 = fs.Read(buffer, 0, buffer.Length)
                baseStream.Write(buffer, 0, numRead)
                fileLength -= numRead
            End While
            MessageBox.Show("File sent")
        Catch exSend As Exception
            MessageBox.Show(exSend.Message)
        End Try
    
        fs.Close()
        baseStream.Close()
        irClient.Close()
    End Sub
    
    // Align the infrared ports of the devices.
    // Click the Receive button first, then click Send.
    private void SendButton_Click(object sender, System.EventArgs e)
    {
        IrDAClient irClient = new IrDAClient();
        string irServiceName = "IrDATest";
        IrDADeviceInfo[] irDevices;
        int buffersize = 256;
    
        // Create a collection of devices to discover.
        irDevices = irClient.DiscoverDevices(2);
    
        // Show the name of the first device found.
        if ((irDevices.Length == 0)) 
        {
            MessageBox.Show("No remote infrared devices found.");
            return;
        }
        try 
        {
            IrDAEndPoint irEndP = 
                new IrDAEndPoint(irDevices[0].DeviceID, irServiceName);
            IrDAListener irListen = new IrDAListener(irEndP);
            irListen.Start();
            irClient = irListen.AcceptIrDAClient();
            MessageBox.Show("Connected!");
        }
        catch (SocketException exSoc) 
        {
            MessageBox.Show(("Couldn\'t listen on service "
                            + (irServiceName + (": " + exSoc.ErrorCode))));
        }
    
        // Open a file to send and get its stream.
        Stream fs;
        try 
        {
            fs = new FileStream(".\\My Documents\\send.txt", FileMode.Open);
        }
        catch (Exception exFile) 
        {
            MessageBox.Show(("Cannot open " + exFile.ToString()));
            return;
        }
    
        // Get the underlying stream of the client.
        Stream baseStream = irClient.GetStream();
    
        // Get the size of the file to send
        // and write its size to the stream.
        byte[] length = BitConverter.GetBytes(fs.Length);
        baseStream.Write(length, 0, length.Length);
    
        // Create a buffer for reading the file.
        byte[] buffer = new byte[buffersize];
        int fileLength = (int) fs.Length;
        try 
        {
            // Read the file stream into the base stream.
            while ((fileLength > 0)) 
            {
                Int64 numRead = fs.Read(buffer, 0, buffer.Length);
                baseStream.Write(buffer, 0, Convert.ToInt32(numRead));
                fileLength = (fileLength - Convert.ToInt32(numRead));
            }
            MessageBox.Show("File sent");
        }
        catch (Exception exSend) 
        {
            MessageBox.Show(exSend.Message);
        }
        fs.Close();
        baseStream.Close();
        irClient.Close();
    }
    
    
  4. Cree una aplicación de Pocket PC para el dispositivo receptor y agregue un botón al formulario. Asigne al botón el nombre Receive.

  5. Agregue el código siguiente para el evento Click del botón Receive.

    ' Align the infrared ports of the devices.
    ' Click the Receive button first, then click Send.
    Private Sub ReceiveButton_Click(sender As Object, e As System.EventArgs) _
        Handles ReceiveButton.Click
    
        Dim irDevices() As IrDADeviceInfo
        Dim irClient As New IrDAClient()
        Dim irServiceName As String = "IrDATest"
    
        Dim buffersize As Integer = 256
    
        ' Create a collection for discovering up to
        ' three devices, although only one is needed.
        irDevices = irClient.DiscoverDevices(2)
    
        ' Cancel if no devices are found.
        If irDevices.Length = 0 Then
            MessageBox.Show("No remote infrared devices found.")
            Return
        End If
    
        ' Connect to the first IrDA device
        Dim irEndP As New IrDAEndPoint(irDevices(0).DeviceID, irServiceName)
        irClient.Connect(irEndP)
    
        ' Create a stream for writing a Pocket Word file.
        Dim writeStream As Stream
        Try
            writeStream = New FileStream(".\My Documents\receive.txt", _
                FileMode.OpenOrCreate)
        Catch
            MessageBox.Show("Cannot open file for writing.")
            Return
        End Try
    
        ' Get the underlying stream of the client.
        Dim baseStream As Stream = irClient.GetStream()
    
        ' Create a buffer for reading the file.
        Dim buffer(buffersize) As Byte
    
        Dim numToRead, numRead As Int64
    
        ' Read the file into a stream 8 bytes at a time.
        ' Because the stream does not support seek operations,
        ' its length cannot be determined.
        numToRead = 8
    
        Try    
            While numToRead > 0
                numRead = baseStream.Read(buffer, 0, numToRead)
                numToRead -= numRead
            End While
        Catch exReadIn As Exception
            MessageBox.Show("Read in: " & exReadIn.Message)
        End Try
    
        ' Get the size of the buffer to show
        ' the number of bytes to write to the file.
        numToRead = BitConverter.ToInt64(buffer, 0)
    
        Try
            ' Write the stream to the file until
            ' there are no more bytes to read.
            While numToRead > 0
                numRead = baseStream.Read(buffer, 0, buffer.Length)
                numToRead -= numRead
                writeStream.Write(buffer, 0, numRead)
            End While
            writeStream.Close()
            MessageBox.Show("File received.")
        Catch exWriteOut As Exception
            MessageBox.Show("Write out: " & exWriteOut.Message)
        End Try
    
         baseStream.Close()
         irClient.Close()
    End Sub
    
    // Align the infrared ports of the devices.
    // Click the Receive button first, then click Send.
    private void ReceiveButton_Click(object sender, System.EventArgs e)
    {
        IrDADeviceInfo[] irDevices;
        IrDAClient irClient = new IrDAClient();
        string irServiceName = "IrDATest";
        int buffersize = 256;
    
        // Create a collection for discovering up to
        // three devices, although only one is needed.
        irDevices = irClient.DiscoverDevices(2);
    
        // Cancel if no devices are found.
        if ((irDevices.Length == 0)) 
        {
            MessageBox.Show("No remote infrared devices found.");
            return;
        }
    
        // Connect to the first IrDA device
        IrDAEndPoint irEndP = 
            new IrDAEndPoint(irDevices[0].DeviceID, irServiceName);
        irClient.Connect(irEndP);
    
        // Create a stream for writing a Pocket Word file.
        Stream writeStream;
        try 
        {
            writeStream = new FileStream(".\\My Documents\\receive.txt", 
                FileMode.OpenOrCreate);
        }
        catch (Exception Ex)
        {
            MessageBox.Show("Cannot open file for writing. " + Ex.Message);
            return;
        }
    
        // Get the underlying stream of the client.
        Stream baseStream = irClient.GetStream();
    
        // Create a buffer for reading the file.
        byte[] buffer = new byte[buffersize];
        Int64 numToRead;
        Int64 numRead;
    
        // Read the file into a stream 8 bytes at a time.
        // Because the stream does not support seek operations, its
        // length cannot be determined.
        numToRead = 8;
        try 
        {
            while ((numToRead > 0)) 
            {
                numRead = baseStream.Read(buffer, 0, 
                    Convert.ToInt32(numToRead));
                numToRead = (numToRead - numRead);
            }
        }
        catch (Exception exReadIn) {
            MessageBox.Show(("Read in: " + exReadIn.Message));
        }
    
        // Get the size of the buffer to show
        // the number of bytes to write to the file.
        numToRead = BitConverter.ToInt64(buffer, 0);
        try 
        {
            // Write the stream to the file until
            // there are no more bytes to read.
            while ((numToRead > 0)) {
                numRead = baseStream.Read(buffer, 0, buffer.Length);
                numToRead = (numToRead - numRead);
                writeStream.Write(buffer, 0, Convert.ToInt32(numRead));
            }
            writeStream.Close();
            MessageBox.Show("File received.");
        }
        catch (Exception exWriteOut) 
        {
            MessageBox.Show(("Write out: " + exWriteOut.Message));
        }
        baseStream.Close();
        irClient.Close();
    }
    

Para ejecutar las aplicaciones

  1. Implemente las aplicaciones en los dispositivos e inícielas.

  2. Alinee los puertos de infrarrojos de los dispositivos.

  3. Puntee el botón Receive en el dispositivo receptor.

  4. Puntee el botón Send en el dispositivo emisor.

  5. Compruebe si se ha creado Receive.txt en la carpeta Mis documentos.

Compilar el código

Para este ejemplo se requieren referencias a los siguientes espacios de nombres:

Vea también

Conceptos

Conexiones de infrarrojos

.Temas "Cómo..." de .NET Compact Framework