C# UDP通讯实例

2021-06-04 05:01

阅读:570

标签:values   art   eve   row   code   local   length   参数   als   

1、发送方代码

void SendMsg(string toip, int port )
        {
            try
            {
                string message="发送内容";
                UdpClient udpclient = new UdpClient();
                IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Parse(ip), port);              
                   
                byte[] data = Encoding.Default.GetBytes(message);
                udpclient.Send(data, data.Length, ipendpoint);
                udpclient.Close();

            }
            catch (Exception ex)
            {

                MessageBox.Show("UDP发送数据" + ex.ToString());
            }

        }

2、接收方代码

 public UdpService udp;

a>实例化、初始化接收事件

udp = new UdpService(fromip, 60000, "127.0.0.1", 60000);
udp.EvtGetValues+=new UdpService.GetRecevice(udp_EvtGetValues);

b>启动UDP

udp.TurnOn();

c>停止UDP

 udp.TurnOff();

d>接收事件处理
 void udp_EvtGetValues(byte[] ReceviceBuff)
        {
            //string message = Encoding.UTF8.GetString(ReceviceBuff, 0, ReceviceBuff.Length);
           //可接收中文内容
           Encoding ei=Encoding.GetEncoding(936);
            string message = ei.GetString(ReceviceBuff, 0, ReceviceBuff.Length);
            if (message.Length > 0)
            {
              // 处理接收逻辑
                
            }
                
        }

 

3、UdpService代码

 public  class UdpService
    {
        #region 内部变量
       
        string devIP = "127.0.0.1";
        int devPort = 60000;
        UdpClient mySocket;
        string meIP = "127.0.0.1";
        int mePort = 60000;
        IPEndPoint RemotePoint;
        bool isRunning = false;
        bool isOpen = false;
        List listThread = new List();       
        string icId = "";
        string cardContent = "";
        byte[] cardContentBuf;
        #endregion

        public UdpService(string ServerIP, int ServerPort, string DevIP, int DevPort)
        {
            this.meIP = ServerIP;
            this.mePort = ServerPort;
            this.devIP = DevIP;
            this.devPort = DevPort;           
            
        }

        #region   

        public void TurnOn()
        {
            try
            {
                if (isOpen) return;
                mySocket = new UdpClient(mePort);
                IPEndPoint ipLocalPoint = new IPEndPoint(IPAddress.Parse(meIP), mePort);

                RemotePoint = new IPEndPoint(IPAddress.Any, devPort);

                isRunning = true;
                Thread thread = new Thread(new ThreadStart(this.ReceiveHandle));
                thread.IsBackground = true;
                thread.Start();
                listThread.Add(thread);
                isOpen = true;

            }
            catch (Exception ex)
            {
                isOpen = false;
                throw new Exception(ex.Message);
            }
        }

        public void TurnOff()
        {
            try
            {
                isOpen = false;
                isRunning = false;

                for (int i = 0; i )
                {
                    try
                    {
                        listThread[i].Abort();
                    }
                    catch (Exception) { }
                }

                if (mySocket != null)
                {
                    mySocket.Close();
                }
            }
            catch (Exception)
            {
            }
        }

        public delegate void GetRecevice(byte[] ReceviceBuff);
        public event GetRecevice EvtGetValues;
        private void ReceiveHandle()
        {
            byte[] sendbuf = new byte[9];
            byte[] sendwritbuf = new byte[200];

            while (isRunning)
            {
                try
                {
                    if (mySocket == null || mySocket.Available 1)
                    {
                        Thread.Sleep(300);
                        continue;
                    }
                    //接收UDP数据报,引用参数RemotePoint获得源地址  
                    byte[] buf = mySocket.Receive(ref RemotePoint);
                    if (devIP == null || devIP.Length 1)
                    {
                        devIP = RemotePoint.Address.ToString();
                        devPort = RemotePoint.Port;
                    }
                    if (EvtGetValues != null)
                    {
                        EvtGetValues(buf);
                    }
                }
                catch (Exception)
                {
                }
            }
        }
        #endregion
    }

 

C# UDP通讯实例

标签:values   art   eve   row   code   local   length   参数   als   

原文地址:https://www.cnblogs.com/lzsin/p/10868814.html


评论


亲,登录后才可以留言!