关闭

C#异步UDP通信

669人阅读 评论(0) 收藏 举报
分类:

[c-sharp] view plaincopy
  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 plaincopy
  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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:364209次
    • 积分:5130
    • 等级:
    • 排名:第5391名
    • 原创:67篇
    • 转载:543篇
    • 译文:0篇
    • 评论:14条
    最新评论