1. 程式人生 > >c# 正在終止執行緒 關閉UdpClient

c# 正在終止執行緒 關閉UdpClient

class Program { // UDP連線static UdpClient udpClient; // 本機埠staticint localhostPort; // 本機IPstatic IPAddress localhostIPAddress; // 本機節點static IPEndPoint localhostIPEndPoint; // 遠端主機結點static IPEndPoint tempEnd =new IPEndPoint(IPAddress.Any, 0); // 判斷是是否釋放Udp連線
staticbool isUdpNull =default(bool); staticvoid Main(string[] args) { // 初始化 Init(); // 非同步接收 udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null); byte[] datagram = Encoding.UTF8.GetBytes("這是一個測試!!!");
//非同步傳送 udpClient.BeginSend(datagram, datagram.Length, localhostIPEndPoint, new AsyncCallback(SendCallback), udpClient); // 停止非同步接收 StopAsynchronousReceive(); Console.ReadKey(); } // 初始化staticvoid Init() { localhostPort =
9000; localhostIPAddress = IPAddress.Parse("127.0.0.1"); localhostIPEndPoint =new IPEndPoint(localhostIPAddress, localhostPort); // 將UDP連線繫結終結點 udpClient =new UdpClient(localhostIPEndPoint); } // 停止非同步接收staticvoid StopAsynchronousReceive() { byte[] datagram =newbyte[] { 0xff }; udpClient.Send(datagram, datagram.Length, localhostIPEndPoint); } // 非同步接收回調方法staticvoid ReceiveCallback(IAsyncResult ar) { object o =newobject(); try { lock (o) { byte[] buffer = udpClient.EndReceive(ar, ref tempEnd); if (tempEnd.Equals(localhostIPEndPoint) && buffer[0] ==0xff) { udpClient.Close(); isUdpNull =true; } else { Console.WriteLine("IP:{0} 訊息內容:"+ Encoding.UTF8.GetString(buffer), tempEnd.Address.ToString()); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { lock (o) { if (!isUdpNull) { udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), null); } } } } // 非同步傳送回撥方法staticvoid SendCallback(IAsyncResult ar) { UdpClient tempUdpClient = (UdpClient)ar.AsyncState; if (tempUdpClient !=null) { Console.WriteLine("傳送的位元組數:{0}", tempUdpClient.EndSend(ar)); } } }