using Apewer; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Apewer.Network { /// UDP 服务端。 public class UdpServer : IDisposable { /// 释放资源。 public void Dispose() { Quit(); } private Thread _thread = null; private System.Net.Sockets.UdpClient _udp = null; private string _address = "0.0.0.0"; private int _port = 0; /// Exception。 public event Event Excepted; /// 服务端已启动。 public event EventHandler Started; /// 服务端已关闭。 public event EventHandler Quitted; /// 已收到客户端数据。 public event SocketReceivedEventHandler Received; /// 构造函数。 public UdpServer() { } /// 服务端是否正在运行。 public bool Alive { get { return (_thread != null) ? _thread.IsAlive : false; } } /// 指定监听地址,默认为 0.0.0.0。 public string Address { get { return _address; } set { if (!Alive) _address = string.IsNullOrEmpty(value) ? "" : value; } } /// 获取或设置服务端端口。 public int Port { get { return _port; } set { int vp = value; if (vp < 0) vp = 0; if (vp > 65535) vp = 65535; if (!Alive) _port = vp; } } /// 启动服务端。 public void Start() { Quit(); var isIP = NetworkUtility.IsIP(_address); if (isIP && (Port > 0)) { _thread = new Thread(Listener); _thread.IsBackground = true; _thread.Start(); } } /// 关闭服务端。 public void Quit() { if (_thread != null) { if (_thread.IsAlive) _thread.Abort(); _thread = null; } if (_udp != null) { _udp.Close(); _udp = null; if (Quitted != null) Quitted(this, new EventArgs()); } } private void Listener() { try { var ep = new IPEndPoint(IPAddress.Any, Port); _udp = new System.Net.Sockets.UdpClient(ep); if (Started != null) Started(this, new EventArgs()); while (true) { var vbytes = _udp.Receive(ref ep); if ((Received != null) && (vbytes.Length > 0)) { Received(this, ep.Address.ToString(), ep.Port, vbytes); } // Thread.Sleep(1); } } catch (Exception ex) { if (Excepted != null) Excepted(this, ex); } if (Quitted != null) Quitted(this, new EventArgs()); } } }