using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace AsyncUdpSever { public class UdpServer { private int _udpPort; private Socket _udpSocket; public UdpServer(int port) { this._udpPort = port; Console.WriteLine("Server Start...@" + port.ToString()); } /// <summary> /// ysl 线程处理 /// </summary> public void Start() { //本地IP与指定端口 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, _udpPort); //服务器Udp Socket _udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); _udpSocket.Bind(ipep); //异步接收 AsyncBeginReceive(); } protected void Stop() { try { _udpSocket.Close(); Thread.Sleep(100); } catch (Exception ex) { Console.WriteLine(ex.Message); } } private void AsyncBeginReceive() { while (true) { try { UdpState state = new UdpState(); state._receiveDone.Reset(); _udpSocket.BeginReceiveFrom( state._data, 0, UdpState._bufferSize, SocketFlags.None, ref state._remoteEndPoint, new AsyncCallback(AsyncReceive), state); Thread.Sleep(100); state._receiveDone.WaitOne(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } /// <summary> /// ysl 异步接收 /// </summary> /// <param name="ar"></param> private void AsyncReceive(IAsyncResult ar) { if (ar.IsCompleted) { try { Console.WriteLine(1 + "line"); UdpState state = (UdpState)ar.AsyncState; //远程发送过来的数据 state._dataLength = _udpSocket.EndReceiveFrom(ar, ref state._remoteEndPoint); Console.WriteLine(2 + "line"); //完成接收 _udpSocket.BeginReceiveFrom( state._data, 0, UdpState._bufferSize, SocketFlags.None, ref state._remoteEndPoint, new AsyncCallback(AsyncReceive), state); Console.WriteLine(3 + "line"); //获取到的报文 string receiveString = Encoding.ASCII.GetString(state._data, 0, state._dataLength); //当前处理完毕 Console.WriteLine(4 + "line"); Console.WriteLine(receiveString); string str = "OK"; byte[] bytes = Encoding.ASCII.GetBytes(str.ToCharArray()); _udpSocket.SendTo(bytes, state._remoteEndPoint); state._receiveDone.Set(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; namespace AsyncUdpSever { public class UdpState { public const int _bufferSize = 4096; public byte[] _data; public int _dataLength; public EndPoint _remoteEndPoint; public UdpState() { this._data = new byte[_bufferSize]; _remoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0); } public UdpState(byte[] data, EndPoint remoteEndPoint) { this._data = data; this._dataLength = data.Length; this._remoteEndPoint = remoteEndPoint; } public ManualResetEvent _receiveDone = new ManualResetEvent(false); } }