C#网络编程系列文章(八)之UdpClient实现同步UDP服务器

本文介绍

udpclient 类在同步阻塞模式中为发送和接收无连接的 udp 数据包而提供了简单的方法。因为 udp 是一种无连接的传输协议,所以你不需要在发送和接收数据之前建立任何远程主机连接。你只需要按照下列方式来建立默认的远程主机选项:
使用远程主机名称和端口号作为参数来创建 udpclient 类的实例。
创建 udpclient 类的实例然后调用 connect 方法。
你可以使用任何由 udpclient 所提供的发送方法把数据发送给远程设备。然后使用 receive 方法来接收来自于远程主机的数据。
提示:如果你已经指定了一个默认的远程主机,就不要使用主机名称或者 ipendpoint 来调用 send 方法。如果你这样做,那么 udpclient 将会抛出一个异常。

UdpClient 方法同样允许你发送和接收多点传送的数据包。而使用 JoinMulticastGroup 方法可以把 UdpClient 订阅到多点传送分组。也可以使用 DropMulticastGroup 方法把 UdpClient 从多点传送分组的订阅中取消。

本节介绍使用UdpClient实现一个同步的UDP服务器

UdpClient同步UDP服务器

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;using System.Net;using System.Threading;namespace NetFrame.Net.UDP.Listener.Synchronous{    ///     /// UdpClient 实现同步UDP服务器    ///     public class UDPServer    {        #region Fields        ///         /// 服务器程序允许的最大客户端连接数        ///         private int _maxClient;        ///         /// 当前的连接的客户端数        ///         //private int _clientCount;        ///         /// 服务器使用的异步UdpClient        ///         private UdpClient _server;        ///         /// 客户端会话列表        ///         //private List _clients;        private bool disposed = false;        ///         /// 数据接受缓冲区        ///         private byte[] _recvBuffer;        #endregion        #region Properties        ///         /// 服务器是否正在运行        ///         public bool IsRunning { get; private set; }        ///         /// 监听的IP地址        ///         public IPAddress Address { get; private set; }        ///         /// 监听的端口        ///         public int Port { get; private set; }        ///         /// 通信使用的编码        ///         public Encoding Encoding { get; set; }        #endregion        #region 构造函数        ///         /// 同步UdpClient UDP服务器        ///         /// 监听的端口        public UDPServer(int listenPort)            : this(IPAddress.Any, listenPort,1024)        {        }        ///         /// 同步UdpClient UDP服务器        ///         /// 监听的终结点        public UDPServer(IPEndPoint localEP)            : this(localEP.Address, localEP.Port,1024)        {        }        ///         /// 同步UdpClient UDP服务器        ///         /// 监听的IP地址        /// 监听的端口        /// 最大客户端数量        public UDPServer(IPAddress localIPAddress, int listenPort, int maxClient)        {            this.Address = localIPAddress;            this.Port = listenPort;            this.Encoding = Encoding.Default;            _maxClient = maxClient;            //_clients = new List();            _server = new UdpClient(new IPEndPoint(this.Address, this.Port));            _recvBuffer=new byte[_server.Client.ReceiveBufferSize];        }        #endregion        #region Method        ///         /// 启动服务器        ///         /// 异步TCP服务器        public void Start()        {            if (!IsRunning)            {                IsRunning = true;                _server.EnableBroadcast = true;                new Thread(ReceiveData).Start();            }        }        ///         /// 停止服务器        ///         public void Stop()        {            if (IsRunning)            {                IsRunning = false;                _server.Close();                //TODO 关闭对所有客户端的连接            }        }        ///         /// 同步接收数据的方法        ///         ///         private void ReceiveData()        {            IPEndPoint remote = null;            while (true)            {                byte[] buffer = null;                try                {                    buffer = _server.Receive(ref remote);                }                catch (Exception)                {                    //异常处理操作                    return;                }                if (buffer == null || buffer.Length == 0) return;                //TODO 数据包收到触发事件                RaiseDataReceived(null);            }        }        ///         /// 同步发送数据        ///         ///         ///         public void Send(string msg, IPEndPoint remote)        {            byte[] data = Encoding.Default.GetBytes(msg);            try            {                _server.Send(data, data.Length, remote);            }            catch (Exception)            {                //TODO 异常处理                RaiseOtherException(null);            }        }        #endregion        #region 事件        ///         /// 接收到数据事件        ///         public event EventHandler DataReceived;        private void RaiseDataReceived(UDPState state)        {            if (DataReceived != null)            {                DataReceived(this, new UDPEventArgs(state));            }        }        ///         /// 数据发送完毕事件        ///         public event EventHandler CompletedSend;        ///         /// 触发数据发送完毕的事件        ///         ///         private void RaiseCompletedSend(UDPState state)        {            if (CompletedSend != null)            {                CompletedSend(this, new UDPEventArgs(state));            }        }        ///         /// 网络错误事件        ///         public event EventHandler NetError;        ///         /// 触发网络错误事件        ///         ///         private void RaiseNetError(UDPState state)        {            if (NetError != null)            {                NetError(this, new UDPEventArgs(state));            }        }        ///         /// 异常事件        ///         public event EventHandler OtherException;        ///         /// 触发异常事件        ///         ///         private void RaiseOtherException(UDPState state, string descrip)        {            if (OtherException != null)            {                OtherException(this, new UDPEventArgs(descrip, state));            }        }        private void RaiseOtherException(UDPState state)        {            RaiseOtherException(state, "");        }        #endregion        #region Close        ///         /// 关闭一个与客户端之间的会话        ///         /// 需要关闭的客户端会话对象        public void Close(UDPState state)        {            if (state != null)            {                //_clients.Remove(state);                //_clientCount--;                //TODO 触发关闭事件            }        }        ///         /// 关闭所有的客户端会话,与所有的客户端连接会断开        ///         public void CloseAllClient()        {            //foreach (AsyncUDPSocketState client in _clients)            //{            //    Close(client);            //}            //_clientCount = 0;            //_clients.Clear();        }        #endregion        #region 释放        ///         /// Performs application-defined tasks associated with freeing,         /// releasing, or resetting unmanaged resources.        ///         public void Dispose()        {            Dispose(true);            GC.SuppressFinalize(this);        }        ///         /// Releases unmanaged and - optionally - managed resources        ///         /// true to release         /// both managed and unmanaged resources; false         /// to release only unmanaged resources.        protected virtual void Dispose(bool disposing)        {            if (!this.disposed)            {                if (disposing)                {                    try                    {                        Stop();                        if (_server != null)                        {                            _server = null;                        }                    }                    catch (SocketException)                    {                        //TODO                        RaiseOtherException(null);                    }                }                disposed = true;            }        }        #endregion    }}

登录后复制

用户状态封装类

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net.Sockets;using System.Net;namespace NetFrame.Net.UDP.Listener.Synchronous{    public class UDPState    {        // Client   socket.        public UdpClient udpClient = null;        // Size of receive buffer.        public const int BufferSize = 1024;        // Receive buffer.        public byte[] buffer = new byte[BufferSize];        // Received data string.        public StringBuilder sb = new StringBuilder();        public IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);    }}

登录后复制

服务器事件参数类

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace NetFrame.Net.UDP.Listener.Synchronous{    ///     /// UdpClient 同步UDP服务器事件类    ///     public class UDPEventArgs : EventArgs    {        ///         /// 提示信息        ///         public string _msg;        ///         /// 客户端状态封装类        ///         public UDPState _state;        ///         /// 是否已经处理过了        ///         public bool IsHandled { get; set; }        public UDPEventArgs(string msg)        {            this._msg = msg;            IsHandled = false;        }        public UDPEventArgs(UDPState state)        {            this._state = state;            IsHandled = false;        }        public UDPEventArgs(string msg, UDPState state)        {            this._msg = msg;            this._state = state;            IsHandled = false;        }    }}

登录后复制

 以上就是C#网络编程系列文章(八)之UdpClient实现同步UDP服务器的内容,更多相关内容请关注PHP中文网(www.php.cn)!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2550491.html

(0)
上一篇 2025年3月6日 05:57:49
下一篇 2025年3月6日 05:57:55

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论