c# 使用udp协议接收消息

引用命名空间

using System.Net;
using System.Net.Sockets;

定义

 private UdpClient Reveive;
 IPAddress localIP = IPAddress.Parse(GetLocalIpv4()[0]);//获取本机ip地址,也可以自己手动填写
 IPEndPoint localIPEndPoint = new IPEndPoint(localIP, 8888);//设置ip和端口
 Reveive = new UdpClient(localIPEndPoint);
 //启动接收线程
 Thread threadReceive = new Thread(ReceiveMessages);//线程回调函数为ReceiveMessages
 threadReceive.IsBackground = true;
 threadReceive.Start();//开启

//获取本机IP

   		private string[] GetLocalIpv4()//获取本机ip
        {
            //事先不知道ip的个数,数组长度未知,因此用StringCollection储存  
            IPAddress[] localIPs;
            localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            StringCollection IpCollection = new StringCollection();
            foreach (IPAddress ip in localIPs)
            {
                //根据AddressFamily判断是否为ipv4,如果是InterNetWorkV6则为ipv6  
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                    IpCollection.Add(ip.ToString());
            }
            string[] IpArray = new string[IpCollection.Count];
            IpCollection.CopyTo(IpArray, 0);
            return IpArray;
        }

//线程回调函数

        private void ReceiveMessages()//线程回调函数
        {
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    byte[] receiveBytes = Reveive.Receive(ref remoteIPEndPoint);
                    string message = System.Text.Encoding.ASCII.GetString(receiveBytes, 0, receiveBytes.Length);
                    string[] date = message.Split('$');
                    Command = date[0];
                    switch (Command)
                    {
                        case "message1":
                             //收到消息:message1
                            break;
                        case "message2": 
                            //收到消息:message2
                            break;
                        default:                          
                            break;
                    }
                }
                catch (Exception e)
                {
                    break;
                }
            }
        }

试试能不能收到消息吧

小结:socket通信中的UDP、TCP还有串口通信的使用方法都大致相似,本文中只讲了应用,具体详细的解析后边我会继续完善,文中若有不足或错误请直接指出,欢迎评论交流。

学习入口:

  1. C#串口通信
  2. C#获取桌面路径
  3. C#串口通信中 16进制与字符串、字节数组之间的转换

你可能感兴趣的:(C#,Socket,c#)