C#基于UDP進行異步通信的方法
更新時間:2015年04月23日 09:37:23 作者:songguo
這篇文章主要介紹了C#基于UDP進行異步通信的方法,實例分析了C#基于UDP實現異步通信的相關技巧,需要的朋友可以參考下
本文實例講述了C#基于UDP進行異步通信的方法。分享給大家供大家參考。具體如下:
服務器端:
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace AsyncServer { public class UdpState { public UdpClient udpClient; public IPEndPoint ipEndPoint; public const int BufferSize = 1024; public byte[] buffer = new byte[BufferSize]; public int counter = 0; } public class AsyncUdpSever { private IPEndPoint ipEndPoint = null; private IPEndPoint remoteEP = null; private UdpClient udpReceive = null; private UdpClient udpSend = null; private const int listenPort = 1100; private const int remotePort = 1101; UdpState udpReceiveState = null; UdpState udpSendState = null; private ManualResetEvent sendDone = new ManualResetEvent(false); private ManualResetEvent receiveDone = new ManualResetEvent(false); public AsyncUdpSever() { ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort); remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0], remotePort); udpReceive = new UdpClient(ipEndPoint); udpSend = new UdpClient(); udpReceiveState = new UdpState(); udpReceiveState.udpClient = udpReceive; udpReceiveState.ipEndPoint = ipEndPoint; udpSendState = new UdpState(); udpSendState.udpClient = udpSend; udpSendState.ipEndPoint = remoteEP; } public void ReceiveMsg() { Console.WriteLine("listening for messages"); while(true) { lock (this) { IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState); receiveDone.WaitOne(); Thread.Sleep(100); } } } private void ReceiveCallback(IAsyncResult iar) { UdpState udpReceiveState = iar.AsyncState as UdpState; if (iar.IsCompleted) { Byte[] receiveBytes = udpReceiveState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint); string receiveString = Encoding.ASCII.GetString(receiveBytes); Console.WriteLine("Received: {0}", receiveString); //Thread.Sleep(100); receiveDone.Set(); SendMsg(); } } private void SendMsg() { udpSend.Connect(udpSendState.ipEndPoint); udpSendState.udpClient = udpSend; udpSendState.counter ++; string message = string.Format("第{0}個UDP請求處理完成!",udpSendState.counter); Byte[] sendBytes = Encoding.Unicode.GetBytes(message); udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState); sendDone.WaitOne(); } private void SendCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; Console.WriteLine("第{0}個請求處理完畢!", udpState.counter); Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar)); sendDone.Set(); } public static void Main() { AsyncUdpSever aus = new AsyncUdpSever(); Thread t = new Thread(new ThreadStart(aus.ReceiveMsg)); t.Start(); Console.Read(); } } }
客戶端:
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace AsyncClient { public class UdpState { public UdpClient udpClient = null; public IPEndPoint ipEndPoint = null; public const int BufferSize = 1024; public byte[] buffer = new byte[BufferSize]; public int counter = 0; } public class AsyncUdpClient { public static bool messageSent = false; // Receive a message and write it to the console. private const int listenPort = 1101; private const int remotePort = 1100; private IPEndPoint localEP = null; private IPEndPoint remoteEP = null; private UdpClient udpReceive = null; private UdpClient udpSend = null; private UdpState udpSendState = null; private UdpState udpReceiveState = null; private int counter = 0; private ManualResetEvent sendDone = new ManualResetEvent(false); private ManualResetEvent receiveDone = new ManualResetEvent(false); private Socket receiveSocket; private Socket sendSocket; public AsyncUdpClient() { localEP = new IPEndPoint(IPAddress.Any, listenPort); remoteEP = new IPEndPoint(Dns.GetHostAddresses(Dns.GetHostName())[0],remotePort); udpReceive = new UdpClient(localEP); udpSend = new UdpClient(); udpSendState = new UdpState(); udpSendState.ipEndPoint = remoteEP; udpSendState.udpClient = udpSend; udpReceiveState = new UdpState(); udpReceiveState.ipEndPoint = remoteEP; udpReceiveState.udpClient = udpReceive; receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); receiveSocket.Bind(localEP); sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sendSocket.Bind(remoteEP); } public void SendMsg() { udpSend.Connect(remoteEP); //Thread t = new Thread(new ThreadStart(ReceiveMessages)); //t.Start(); Byte[] sendBytes; string message; while (true) { message = "Client" + (counter++).ToString(); lock (this) { sendBytes = Encoding.ASCII.GetBytes(message); udpSendState.counter = counter; udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState); sendDone.WaitOne(); Thread.Sleep(200); ReceiveMessages(); } } } public void SendCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; if (iar.IsCompleted) { Console.WriteLine("第{0}個發(fā)送完畢!", udpState.counter); Console.WriteLine("number of bytes sent: {0}", udpState.udpClient.EndSend(iar)); //if (udpState.counter == 10) //{ // udpState.udpClient.Close(); //} sendDone.Set(); } } public void ReceiveMessages() { lock (this) { udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceiveState); receiveDone.WaitOne(); Thread.Sleep(100); } } public void ReceiveCallback(IAsyncResult iar) { UdpState udpState = iar.AsyncState as UdpState; if (iar.IsCompleted) { Byte[] receiveBytes = udpState.udpClient.EndReceive(iar, ref udpReceiveState.ipEndPoint); string receiveString = Encoding.Unicode.GetString(receiveBytes); Console.WriteLine("Received: {0}", receiveString); receiveDone.Set(); } } public static void Main() { AsyncUdpClient auc = new AsyncUdpClient(); auc.SendMsg(); Console.Read(); } } }
希望本文所述對大家的C#程序設計有所幫助。
相關文章
C# 文件上傳下載(Excel導入,多線程下載)功能的實現代碼
這篇文章主要介紹了C# 文件上傳下載(Excel導入,多線程下載)功能的實現代碼,需要的朋友可以參考下2017-08-08Unity實戰(zhàn)之FlyPin(見縫插針)小游戲的實現
這篇文章主要介紹了利用Unity制作FlyPin(見縫插針)小游戲的實現方法,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起試一試2022-01-01DevExpress之ChartControl實現餅狀圖百分比演示實例
這篇文章主要介紹了DevExpress之ChartControl實現餅狀圖百分比演示的方法,實例講述了窗體與圖形繪制函數的用法,需要的朋友可以參考下2014-10-10關于C#.net winform程序驗證moss的集成身份認證實例
因為網站使用的是windows集成認證,所以遇到了權限問題,需要輸入密碼。使操作和用戶體驗非常不方便,研究了好久沒有找到好的方法,最后終于讓我踏破鐵鞋總結出了下面的方法2013-03-03C# winform 請求http的實現(get,post)
本文主要介紹了C# winform 請求http的實現(get,post),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06