C# UdpClient使用

Posted yaosj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# UdpClient使用相关的知识,希望对你有一定的参考价值。

 

客户端:

    public class UdpClientManager
    
        //接收数据事件
        public Action<string> recvMessageEvent = null;
        //发送结果事件
        public Action<int> sendResultEvent = null;

        private UdpClient udpClient = null;

        public UdpClientManager()
        
        

        public void Start()
        
            while (true)
            
                try
                
                    udpClient = new UdpClient(destPort, AddressFamily.InterNetwork);//指定本地监听port
                    ReceiveMessage();
                    break;
                
                catch (Exception)
                
                    Thread.Sleep(100);
                
            
        

        private async void ReceiveMessage()
        
            while (true)
            
                if (udpClient == null)
                    return;

                try
                
                    UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
                    string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
                    if (recvMessageEvent != null)
                        recvMessageEvent(message);
                
                catch (Exception ex)
                
                
            
        

        //单播
        public async void SendMessageByUnicast(string message, string destHost, int destPort)
        
            if (string.IsNullOrEmpty(message))
                throw new ArgumentNullException("message cant not null");
            if (udpClient == null)
                throw new ArgumentNullException("udpClient cant not null");
            if (string.IsNullOrEmpty(destHost))
                throw new ArgumentNullException("destHost cant not null");
            if (destPort < 0 || destPort > 65535)
                throw new ArgumentOutOfRangeException("destPort is out of range");

            byte[] buffer = Encoding.UTF8.GetBytes(message);
            int len = 0;
            for (int i = 0; i < 3; i++)
            
                try
                
                    len = await udpClient.SendAsync(buffer, buffer.Length, new IPEndPoint(IPAddress.Parse(destHost), destPort));
                
                catch (Exception)
                
                    len = 0;
                

                if (len <= 0)
                    Thread.Sleep(100);
                else
                    break;
            

            if (sendResultEvent != null)
                sendResultEvent(len);
        

        public void CloseUdpCliend()
        
            if (udpClient == null)
                throw new ArgumentNullException("udpClient cant not null");

            try
            
                udpClient.Client.Shutdown(SocketShutdown.Both);
            
            catch (Exception)
            
            
            udpClient.Close();
            udpClient = null;
        
    

  

服务器:

    public class UdpServiceManager
    
        private readonly string broadCastHost = "255.255.255.255";
        //接收数据事件
        public Action<string> recvMessageEvent = null;
        //发送结果事件
        public Action<int> sendResultEvent = null;
        //本地host
        private string localHost = "";
        //本地port
        private int localPort = 0;

        private UdpClient udpClient = null;

        public UdpServiceManager(string localHost, int localPort)
        
            if (string.IsNullOrEmpty(localHost))
                throw new ArgumentNullException("localHost cant not null");
            if (localPort < 0 || localPort > 65535)
                throw new ArgumentOutOfRangeException("localPort is out of range");

            this.localHost = localHost;
            this.localPort = localPort;
        

        public void Start()
        
            while (true)
            
                try
                
                    udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse(localHost), localPort));//绑定本地host和port
                    ReceiveMessage();
                    break;
                
                catch (Exception)
                
                    Thread.Sleep(100);
                
            
        

        private async void ReceiveMessage()
        
            while (true)
            
                if (udpClient == null)
                    return;

                try
                
                    UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
                    string message = Encoding.UTF8.GetString(udpReceiveResult.Buffer);
                    if (recvMessageEvent != null)
                        recvMessageEvent(message);
                
                catch (Exception)
                
                
            
        

        //单播
        public async void SendMessageByUnicast(string message, string destHost, int destPort)
        
            if (string.IsNullOrEmpty(message))
                throw new ArgumentNullException("message cant not null");
            if (string.IsNullOrEmpty(destHost))
                throw new ArgumentNullException("destHost cant not null");
            if (destPort < 0 || destPort > 65535)
                throw new ArgumentOutOfRangeException("destPort is out of range");
            if (udpClient == null)
                throw new ArgumentNullException("udpClient cant not null");

            byte[] buffer = Encoding.UTF8.GetBytes(message);
            int len = 0;
            for (int i = 0; i < 3; i++)
            
                try
                
                    len = await udpClient.SendAsync(buffer, buffer.Length, destHost, destPort);
                
                catch (Exception)
                
                    len = 0;
                

                if (len <= 0)
                    Thread.Sleep(100);
                else
                    break;
            

            if (sendResultEvent != null)
                sendResultEvent(len);
        

        //广播
        public async void SendMessageByBroadcast(string message)
        
            if (string.IsNullOrEmpty(message))
                throw new ArgumentNullException("message cant not null");
            if (udpClient == null)
                throw new ArgumentNullException("udpClient cant not null");

            byte[] buffer = Encoding.UTF8.GetBytes(message);
            int len = 0;
            for (int i = 0; i < 3; i++)
            
                try
                
                    len = await udpClient.SendAsync(buffer, buffer.Length, broadCastHost, localPort);
                
                catch (Exception ex)
                
                    len = 0;
                

                if (len <= 0)
                    Thread.Sleep(100);
                else
                    break;
            

            if (sendResultEvent != null)
                sendResultEvent(len);
        

        public void CloseUdpCliend()
        
            if (udpClient == null)
                throw new ArgumentNullException("udpClient cant not null");

            try
            
                udpClient.Client.Shutdown(SocketShutdown.Both);
            
            catch (Exception)
            
            
            udpClient.Close();
            udpClient = null;
        
    

  

以上是关于C# UdpClient使用的主要内容,如果未能解决你的问题,请参考以下文章

C#:UdpClient 很快调用 close() 时不发送数据

C# UdpClient使用

使用 UdpClient C# 发送对象

C# UdpClient 设置超时时间

C#里使用UdpClient和线程来创建UDP网络通讯

C#里使用UdpClient和线程来创建UDP网络通讯