• C# UdpClient使用


    客户端:

        public class UdpClientManager
        {
            //接收数据事件
            public Action<string> recvMessageEvent = null;
            //发送结果事件
            public Action<int> sendResultEvent = null;
            //本地监听端口
            public int localPort = 0;
    
            private UdpClient udpClient = null;
    
            public UdpClientManager(int localPort)
            {
                if (localPort < 0 || localPort > 65535)
                    throw new ArgumentOutOfRangeException("localPort is out of range");
    
                this.localPort = localPort;
            }
    
            public void Start()
            {
                while (true)
                {
                    try
                    {
                        udpClient = new UdpClient(localPort, 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;
            }
        }
    

      

    多播方式

       public class UdpClientManager
        {
            //接收数据事件
            public Action<string> recvMessageEvent = null;
            //发送结果事件
            public Action<int> sendResultEvent = null;
            //本地监听端口
            public int localPort = 0;
            //组播地址
            public string MultiCastHost = "";
    
            private UdpClient udpClient = null;
    
            public UdpClientManager(int localPort, string MultiCastHost)
            {
                if (localPort < 0 || localPort > 65535)
                    throw new ArgumentOutOfRangeException("localPort is out of range");
                if (string.IsNullOrEmpty(MultiCastHost))
                    throw new ArgumentNullException("message cant not null");
    
                this.localPort = localPort;
                this.MultiCastHost = MultiCastHost;
            }
    
            public void Start()
            {
                while (true)
                {
                    try
                    {
                        udpClient = new UdpClient(localPort, AddressFamily.InterNetwork);//指定本地监听port
                        udpClient.JoinMulticastGroup(IPAddress.Parse(MultiCastHost));
                        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 SendMessageByMulticast(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, new IPEndPoint(IPAddress.Parse(MultiCastHost), localPort));
                    }
                    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;
            }
        }
    

      

  • 相关阅读:
    git 只添加cpp文件
    URI和URL学习
    scanpy中常用函数
    特征去量纲方法
    排列组合数计算公式
    UML图
    行测图形推理笔记-
    nis服务器实现用户帐号管理同步
    rsh配置双方主机免密
    两周实习的总结
  • 原文地址:https://www.cnblogs.com/yaosj/p/11226577.html
Copyright © 2020-2023  润新知