码迷,mamicode.com
首页 > Windows程序 > 详细

C# UdpClient使用

时间:2019-07-22 16:45:16      阅读:472      评论:0      收藏:0      [点我收藏+]

标签:||   cat   argument   encoding   arp   event   ipaddr   bre   ica   

 

客户端:

    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使用

标签:||   cat   argument   encoding   arp   event   ipaddr   bre   ica   

原文地址:https://www.cnblogs.com/yaosj/p/11226577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!