C#异步UDP通信

[c-sharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Net;  
  5. using System.Net.Sockets;  
  6. using System.Threading;  
  7. namespace AsyncServer  
  8. {  
  9.     public class UdpState  
  10.     {  
  11.         public UdpClient udpClient;  
  12.         public IPEndPoint ipEndPoint;  
  13.         public const int BufferSize = 1024;  
  14.         public byte[] buffer = new byte[BufferSize];  
  15.         public int counter = 0;  
  16.     }  
  17.     public class AsyncUdpSever  
  18.     {  
  19.         private IPEndPoint ipEndPoint = null;  
  20.         private IPEndPoint remoteEP = null;  
  21.         private UdpClient udpReceive = null;  
  22.         private UdpClient udpSend = null;  
  23.         private const int listenPort = 1100;  
  24.         private const int remotePort = 1101;  
  25.         UdpState udpReceiveState = null;  
  26.         UdpState udpSendState = null;  
  27.         private ManualResetEvent sendDone = new ManualResetEvent(false);  
  28.         private ManualResetEvent receiveDone = new ManualResetEvent(false);  
  29.         public AsyncUdpSever()  
  30.         {  
  31.             ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort);  
  32.             remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort);  
  33.             udpReceive = new UdpClient(ipEndPoint);  
  34.             udpSend = new UdpClient();  
  35.             udpReceiveState = new UdpState();              
  36.             udpReceiveState.udpClient = udpReceive;  
  37.             udpReceiveState.ipEndPoint = ipEndPoint;  
  38.   
  39.             udpSendState = new UdpState();  
  40.             udpSendState.udpClient = udpSend;  
  41.             udpSendState.ipEndPoint = remoteEP;  
  42.         }  
  43.         public void ReceiveMsg()  
  44.         {  
  45.             Console.WriteLine("listening for messages");  
  46.             while(true)  
  47.             {  
  48.                 lock (this)  
  49.                 {     
  50.                     IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);  
  51.                     receiveDone.WaitOne();  
  52.                     Thread.Sleep(100);  
  53.                 }  
  54.             }  
  55.         }  
  56.         private void ReceiveCallback(IAsyncResult iar)  
  57.         {  
  58.             UdpState udpReceiveState = iar.AsyncState as UdpState;  
  59.             if (iar.IsCompleted)  
  60.             {  
  61.                 Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);  
  62.                 string receiveString = Encoding.ASCII.GetString(receiveBytes);  
  63.                 Console.WriteLine("Received: {0}", receiveString);  
  64.                 //Thread.Sleep(100);  
  65.                 receiveDone.Set();  
  66.                 SendMsg();  
  67.             }  
  68.         }  
  69.   
  70.         private void SendMsg()  
  71.         {  
  72.             udpSend.Connect(udpSendState.ipEndPoint);  
  73.             udpSendState.udpClient = udpSend;  
  74.             udpSendState.counter ++;  
  75.   
  76.             string message = string.Format("第{0}个UDP请求处理完成!",udpSendState.counter);  
  77.             Byte[] sendBytes = Encoding.Unicode.GetBytes(message);  
  78.             udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);  
  79.             sendDone.WaitOne();  
  80.         }  
  81.         private void SendCallback(IAsyncResult iar)  
  82.         {  
  83.             UdpState udpState = iar.AsyncState as UdpState;  
  84.             Console.WriteLine("第{0}个请求处理完毕!", udpState.counter);  
  85.             Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));  
  86.             sendDone.Set();  
  87.         }  
  88.   
  89.         public static void Main()  
  90.         {  
  91.             AsyncUdpSever aus = new AsyncUdpSever();  
  92.             Thread t = new Thread(new ThreadStart(aus.ReceiveMsg));  
  93.             t.Start();  
  94.             Console.Read();  
  95.         }  
  96.     }  
  97. }  
[c-sharp]  view plain copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Net;  
  5. using System.Net.Sockets;  
  6. using System.Threading;  
  7. namespace AsyncClient  
  8. {  
  9.     public class UdpState  
  10.     {  
  11.         public UdpClient udpClient = null;  
  12.         public IPEndPoint ipEndPoint = null;  
  13.         public const int BufferSize = 1024;  
  14.         public byte[] buffer = new byte[BufferSize];  
  15.         public int counter = 0;  
  16.     }  
  17.     public class AsyncUdpClient  
  18.     {  
  19.         public static bool messageSent = false;  
  20.         // Receive a message and write it to the console.  
  21.         private const int listenPort = 1101;  
  22.         private const int remotePort = 1100;  
  23.         private IPEndPoint localEP = null;  
  24.         private IPEndPoint remoteEP = null;  
  25.         private UdpClient udpReceive = null;  
  26.         private UdpClient udpSend = null;  
  27.         private UdpState udpSendState = null;  
  28.         private UdpState udpReceiveState = null;  
  29.         private int counter = 0;  
  30.         private ManualResetEvent sendDone = new ManualResetEvent(false);  
  31.         private ManualResetEvent receiveDone = new ManualResetEvent(false);  
  32.         private Socket receiveSocket;  
  33.         private Socket sendSocket;  
  34.         public AsyncUdpClient()  
  35.         {  
  36.             localEP = new IPEndPoint(IPAddress.Any, listenPort);  
  37.             remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0],remotePort);  
  38.             udpReceive = new UdpClient(localEP);              
  39.             udpSend = new UdpClient();  
  40.               
  41.             udpSendState = new UdpState();  
  42.             udpSendState.ipEndPoint = remoteEP;  
  43.             udpSendState.udpClient = udpSend;  
  44.   
  45.             udpReceiveState = new UdpState();  
  46.             udpReceiveState.ipEndPoint = remoteEP;  
  47.             udpReceiveState.udpClient = udpReceive;  
  48.   
  49.             receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
  50.             receiveSocket.Bind(localEP);  
  51.   
  52.             sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  
  53.             sendSocket.Bind(remoteEP);  
  54.         }  
  55.         public void SendMsg()  
  56.         {     
  57.             udpSend.Connect(remoteEP);  
  58.               
  59.             //Thread t = new Thread(new ThreadStart(ReceiveMessages));  
  60.             //t.Start();  
  61.             Byte[] sendBytes;  
  62.             string message;              
  63.             while (true)  
  64.             {     
  65.                 message = "Client" + (counter++).ToString();  
  66.                 lock (this)  
  67.                 {  
  68.                     sendBytes = Encoding.ASCII.GetBytes(message);  
  69.                     udpSendState.counter = counter;  
  70.                     udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);  
  71.                     sendDone.WaitOne();  
  72.                     Thread.Sleep(200);  
  73.                     ReceiveMessages();  
  74.                 }  
  75.             }               
  76.         }  
  77.   
  78.         public void SendCallback(IAsyncResult iar)  
  79.         {  
  80.             UdpState udpState = iar.AsyncState as UdpState;  
  81.             if (iar.IsCompleted)  
  82.             {  
  83.                 Console.WriteLine("第{0}个发送完毕!", udpState.counter);  
  84.                 Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar));  
  85.                 //if (udpState.counter == 10)  
  86.                 //{  
  87.                 //    udpState.udpClient.Close();  
  88.                 //}  
  89.                 sendDone.Set();  
  90.             }              
  91.         }  
  92.   
  93.         public void ReceiveMessages()  
  94.         {  
  95.             lock (this)  
  96.             {  
  97.                 udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState);  
  98.                 receiveDone.WaitOne();  
  99.                 Thread.Sleep(100);  
  100.             }     
  101.         }  
  102.         public void ReceiveCallback(IAsyncResult iar)  
  103.         {  
  104.             UdpState udpState = iar.AsyncState as UdpState;  
  105.             if (iar.IsCompleted)  
  106.             {  
  107.                 Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint);  
  108.                 string receiveString = Encoding.Unicode.GetString(receiveBytes);  
  109.                 Console.WriteLine("Received: {0}", receiveString);  
  110.                 receiveDone.Set();  
  111.             }              
  112.         }  
  113.           
  114.         public static void Main()  
  115.         {  
  116.             AsyncUdpClient auc = new AsyncUdpClient();  
  117.             auc.SendMsg();  
  118.             Console.Read();  
  119.         }  
  120.     }  
  121. }  

前天一个朋友让我帮忙写一个异步UDP通信的例子,于是参考了下MSDN修改了上面的代码,比较丑陋,主要是看看运行的功能。

后来准备把里面的UdpClient换成Socket来实现,但是碰到了个问题。但列文章写出来,共同探讨探讨。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于Hololens可以运行Windows 10操作系统,因此可以使用C#语言编写UDP通信代码。以下是一个简单的Hololens UDP通信代码示例: 发送端代码: ```csharp using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine; public class UDPSender : MonoBehaviour { public string remoteIP = "192.168.0.2"; // 远程IP地址 public int remotePort = 12345; // 远程端口号 private UdpClient udpClient; void Start() { udpClient = new UdpClient(); } void Update() { string message = "Hello, World!"; // 要发送的消息 byte[] data = Encoding.UTF8.GetBytes(message); // 将消息转换为字节数组 udpClient.Send(data, data.Length, remoteIP, remotePort); // 发送消息 } void OnApplicationQuit() { udpClient.Close(); // 关闭UDP客户端 } } ``` 接收端代码: ```csharp using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using UnityEngine; public class UDPReceiver : MonoBehaviour { public int localPort = 12345; // 本地端口号 private UdpClient udpClient; void Start() { udpClient = new UdpClient(localPort); // 创建UDP客户端并绑定本地端口号 udpClient.BeginReceive(ReceiveCallback, null); // 开始异步接收消息 } void ReceiveCallback(IAsyncResult result) { IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); byte[] data = udpClient.EndReceive(result, ref remoteEP); // 结束异步接收消息,并获取远程IP和端口号 string message = Encoding.UTF8.GetString(data); // 将字节数组转换为字符串 Debug.Log("Received message: " + message); udpClient.BeginReceive(ReceiveCallback, null); // 再次开始异步接收消息 } void OnApplicationQuit() { udpClient.Close(); // 关闭UDP客户端 } } ``` 发送端代码中使用了`UdpClient`类的`Send`方法将消息发送给指定的远程IP和端口号。接收端代码中使用了`UdpClient`类的`BeginReceive`方法开始异步接收消息,接收到消息后会调用`ReceiveCallback`方法处理消息。在`ReceiveCallback`方法中,使用`UdpClient`类的`EndReceive`方法获取接收到的消息和远程IP和端口号,并将消息转换为字符串。最后再次调用`BeginReceive`方法开始下一次异步接收消息。在应用程序退出时,需要调用`Close`方法关闭UDP客户端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值