Q/chen.NET之园

…………………………………………C#toWindows Mobile&Asp.NET
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.NET CF中的红外通讯

Posted on 2007-05-02 18:12  Q/chen  阅读(961)  评论(1编辑  收藏  举报
C#代码:
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace IrDATextTransmitter
{
    
/// <summary>
    
/// Summary description for Form1.
    
/// </summary>

    public class Form1 : System.Windows.Forms.Form
    
{
        
internal System.Windows.Forms.TextBox sendReceiveTextBox;
        
internal System.Windows.Forms.MenuItem exitMenuItem;
        
internal System.Windows.Forms.MenuItem MenuItem1;
        
internal System.Windows.Forms.Button receiveButton;
        
internal System.Windows.Forms.Button sendButton;
        
internal System.Windows.Forms.MainMenu MainMenu1;

        
private string serviceName = "IRDA_SOCKET_CONNECTION";

        
public Form1()
        
{
            
//
            
// Required for Windows Form Designer support
            
//
            InitializeComponent();

            
//
            
// TODO: Add any constructor code after InitializeComponent call
            
//
        }

        
/// <summary>
        
/// Clean up any resources being used.
        
/// </summary>

        protected override void Dispose( bool disposing )
        
{
            
base.Dispose( disposing );
        }

        
Windows Form Designer generated code

        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>


        
static void Main() 
        
{
            Application.Run(
new Form1());
        }



        
private byte[] WaitToReadIRData()
        
{
            
byte[] bytesRead = new byte[128];
            IrDAListener listener 
= new IrDAListener(serviceName);
            IrDAClient client 
= null;
            System.IO.Stream stream 
= null;

            
try
            
{
                listener.Start();
                client 
= listener.AcceptIrDAClient();  // blocking call
                stream = client.GetStream();
                stream.Read(bytesRead, 
0128);
            }


            
finally
            
{
                
if (stream != null)
                
{
                    stream.Close();
                }

                
if (client != null)
                
{
                    client.Close();
                }

                listener.Stop();
            }


            
return bytesRead;
        }



        
private void SendIRData(int numRetries, byte[] buffer, int bufferLen)
        
{
            IrDAClient client 
= null;
            
int currentTries = 1;

            sendButton.Enabled 
= false;

            
do
            
{
                
try
                
{
                    client 
= new IrDAClient(serviceName);
                }

                
catch (SocketException se)
                
{
                    
if (currentTries > numRetries)
                    
{
                        
throw se;
                    }

                    
else
                    
{
                        MessageBox.Show(
"Peer is not in listening mode. Enable listening mode by clicking the Receive button""Attempt " + currentTries.ToString() + " of " + numRetries.ToString());
                    }

                }

                
catch (Exception)
                
{
                    MessageBox.Show(
"Connection not found. Align infrared ports and try again""Attempt " + currentTries.ToString() + " of " + numRetries.ToString());
                }

                currentTries 
= currentTries + 1;
            }

            
while ((client == null&& (currentTries - 1 < numRetries));

            
if (client == null)
            
{
                
// timeout occurred
                throw new SocketException();
            }

            
            System.IO.Stream stream 
= null;
            
try
            
{
                stream 
= client.GetStream();
                stream.Write(buffer, 
0, bufferLen);
            }

            
finally
            
{
                
if (stream != null)
                
{
                    stream.Close();
                }

                client.Close();
            }


            sendButton.Enabled 
= true;
        }



        
private void receiveButton_Click(object sender, System.EventArgs e)
        
{
            
byte[] readBuf;
            
string readString;

            receiveButton.Enabled 
= false;
            
// this is a blocking call
            readBuf = WaitToReadIRData();

            readString 
= ConvertBytesToString(readBuf);
            sendReceiveTextBox.Text 
= readString;

            receiveButton.Enabled 
= true;
        }


        
private void sendButton_Click(object sender, System.EventArgs e)
        
{
            
string stringValue = sendReceiveTextBox.Text;
            
byte[] byteBuffer;
            byteBuffer 
= ConvertStringToBytes(stringValue, stringValue.Length);
            SendIRData(
5, byteBuffer, stringValue.Length);
        }


        
private void exitMenuItem_Click(object sender, System.EventArgs e)
        
{
            Application.Exit();
        }


        
private byte[] ConvertStringToBytes(string stringValue, int stringLength)
        
{
            
char charValue;
            
int counter;
            
byte[] byteBuffer = new byte[stringLength];

            
for (counter = 0; counter < stringLength; counter++)
            
{
                charValue 
= stringValue[counter];
                byteBuffer[counter] 
= Convert.ToByte(charValue);
            }


            
return byteBuffer;
        }


        
private string ConvertBytesToString(byte[] byteBuffer)
        
{
            StringBuilder sb 
= new StringBuilder();
            
int counter;

            
for (counter = 0; counter < byteBuffer.Length; counter++)
            
{
                sb.Append(Convert.ToChar(byteBuffer[counter]));
            }


            
return sb.ToString();
        }

    }

}

VB.NET代码:
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class Form1

    
Inherits System.Windows.Forms.Form
    
Friend WithEvents sendReceiveTextBox As System.Windows.Forms.TextBox
    
Friend WithEvents sendButton As System.Windows.Forms.Button
    
Friend WithEvents receiveButton As System.Windows.Forms.Button
    
Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu

    
Private serviceName As String = "IRDA_SOCKET_CONNECTION"

Windows Form Designer generated code

    
Private Sub ReceiveData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles receiveButton.Click

        
Dim readBuf() As Byte
        
Dim readString As String

        receiveButton.Enabled 
= False
        
' this is a blocking call
        readBuf = WaitToReadIRData()

        readString 
= ConvertBytesToString(readBuf)
        sendReceiveTextBox.Text 
= readString

        receiveButton.Enabled 
= True

    
End Sub


    
Private Function WaitToReadIRData() As Byte()

        
Dim bytesRead(128As Byte
        
Dim listener As IrDAListener = New IrDAListener(serviceName)
        
Dim client As IrDAClient = Nothing
        
Dim stream As System.IO.Stream = Nothing

        
Try
            listener.Start()
            client 
= listener.AcceptIrDAClient()  ' blocking call
            stream = client.GetStream()
            stream.Read(bytesRead, 
0128)

        
Finally

            
If (Not stream Is NothingThen
                stream.Close()
            
End If

            
If (Not client Is NothingThen
                client.Close()
            
End If

            listener.Stop()
        
End Try

        
Return bytesRead

    
End Function

    
Private Sub SendIRData(ByVal numRetries As IntegerByVal buffer() As ByteByVal bufferLen As Integer)

        
Dim client As IrDAClient = Nothing
        
Dim currentTries As Integer = 1

        sendButton.Enabled 
= False

        
Do
            
Try
                client 
= New IrDAClient(serviceName)
            
Catch se As SocketException
                
If (currentTries > numRetries) Then
                    
Throw se
                
Else
                    MessageBox.Show(
"Peer is not in listening mode. Enable listening mode by clicking the Receive button""Attempt " & currentTries & " of " & numRetries)
                
End If
            
Catch e As Exception
                MessageBox.Show(
"Connection not found. Align infrared ports and try again""Attempt " & CurrentTries & " of " & NumRetries)
            
End Try
            currentTries 
= currentTries + 1

        
Loop While client Is Nothing And currentTries - 1 < numRetries

        
If (client Is NothingThen
            
'timeout occurred
            Throw New SocketException
        
End If

        
Dim stream As System.IO.Stream = Nothing
        
Try
            stream 
= client.GetStream()
            stream.Write(buffer, 
0, bufferLen)
        
Finally
            
If (Not stream Is NothingThen
                stream.Close()
            
End If
            client.Close()
        
End Try

        sendButton.Enabled 
= True

    
End Sub


    
Private Sub sendButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendButton.Click

        
Dim stringValue As String = sendReceiveTextBox.Text
        
Dim byteBuffer() As Byte
        byteBuffer 
= ConvertStringToBytes(stringValue, stringValue.Length)
        SendIRData(
5, byteBuffer, stringValue.Length)

    
End Sub


    
Private Sub exitMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles exitMenuItem.Click
        Application.Exit()
    
End Sub


    
Private Function ConvertStringToBytes(ByVal stringValue As StringByVal stringLength As IntegerAs Byte()

        
Dim charValue As Char
        
Dim counter As Integer
        
Dim byteBuffer(stringLength) As Byte

        
For counter = 0 To stringLength - 1
            charValue 
= stringValue.Chars(counter)
            byteBuffer(counter) 
= Convert.ToByte(charValue)
        
Next

        
Return byteBuffer

    
End Function


    
Private Function ConvertBytesToString(ByVal byteBuffer() As ByteAs String

        
Dim sb As New StringBuilder
        
Dim counter As Integer

        
For counter = 0 To byteBuffer.Length - 1
            sb.Append(Convert.ToChar(byteBuffer(counter)))
        
Next

        
Return sb.ToString

    
End Function


End Class



使用方式:
1、编译好之后,部署到两台PPC上面,并运行起来。
2、将两台PPC红外对准。
3、按下A机的receive按钮
4、在B机的TextBox中输入字符串,点击Send
5、A机可以收到B发出的字符串
6、反之亦可。