(C#)使用udp协议实现消息的接收

1.udp-服务器端的实现

使用udp协议传输数据不需要建立连接

第一步创建Socket,第二步给服务器的Socket绑定ip和port,这个Socket就可以通过这个ip和port接收数据了。

第三步接收数据,在本例中通过新建线程的方式来接收数据,将线程设置为后台线程,这样在进程结束的时候,接收数据也不需要了。在ReceiveMessage的函数中实现了接收数据。ReceiveFrom的方法将数据存入data中,将数据来源的ip和port存入了一个EndPoint中。

class Program
    {
        private static Socket udpServer;
        static void Main(string[] args)
        {
            //1.Socket creat
            udpServer = new Socket
                (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            
            //2.Bind ip and port
            udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.103"),7788));

            //3.receive data
            new Thread(ReceiveMessage) {
                IsBackground = true}.Start();
            
            Console.ReadKey();
        }
        static void ReceiveMessage()
        {
            while (true)
            {
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = new byte[1024];
                int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//此方法把数据来源ip、port放到第二个参数中
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine
                    ("从ip" + (remoteEndPoint as IPEndPoint).Address.ToString()
                    + ":" + (remoteEndPoint as IPEndPoint).Port + "Get" + message);
            }
        }
    }

2.udp-客户端的实现

在客户端只需要创建Socket,给Socket指定目标的ip和port,向这个EndPoint发送数据就可以了

class Program
    {
        static void Main(string[] args)
        {
            //创建Socket
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            // Send message
            while (true)
            {
                EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.103"), 7788);
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                udpClient.SendTo(data, serverPoint);
            }

            udpClient.Close();
            Console.ReadKey();
        }
    }

猜你喜欢

转载自blog.csdn.net/Game_Builder/article/details/81263031
今日推荐