c# UdpClient类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/i1tws/article/details/86630637
    public class CxnUDPClient
    {
        private UdpClient _udpClient;
        private string _remoteHost;
        private int _remotePort;
        private bool _isStopThread = false;

        //远程ip  远程端口
        public CxnUDPClient(string remoteHost,int remotePort)
        {
            _remoteHost = remoteHost;
            _remotePort = remotePort;
            Connect();

            //异步接收消息
            Thread tdRecv = new Thread(OnRecvThread);
            tdRecv.IsBackground = true;
            tdRecv.Start();
        }

        public void Connect()
        {
            if (_udpClient != null)Close();
            _udpClient = new UdpClient(_remoteHost,_remotePort);
        }

        public void Close()
        {
            _isStopThread = true;
            _udpClient.Close();
            _udpClient = null;
        }

        private void OnRecvThread()
        {
            try
            {
                while (true)
                {
                    if (_isStopThread)
                    {
                        return;
                    }

                    IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);//保存发送方的ip和端口号
                    byte[] buffer = _udpClient.Receive(ref point);
                    string msg = Encoding.ASCII.GetString(buffer, 0, buffer.Length);//

                    Console.WriteLine("接收消息:{0}",msg);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public bool Send(string message)
        {
            try
            {
                byte[] data = Encoding.ASCII.GetBytes(message);
                _udpClient.Send(data, data.Length);

                return true;
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/i1tws/article/details/86630637