C#中使用UDP通信

UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。

服务器端代码:

C#代码  收藏代码
  1. static void Main(string[] args)  
  2.         {  
  3.             UdpClient client = null;  
  4.             string receiveString = null;  
  5.             byte[] receiveData = null;  
  6.             //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点  
  7.             IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);  
  8.   
  9.             while (true)  
  10.             {  
  11.                 client = new UdpClient(11000);  
  12.                 receiveData = client.Receive(ref remotePoint);//接收数据  
  13.                 receiveString = Encoding.Default.GetString(receiveData);  
  14.                 Console.WriteLine(receiveString);  
  15.                 client.Close();//关闭连接  
  16.             }  
  17.         }  

 客户端代码:

C#代码  收藏代码
  1. static void Main(string[] args)  
  2.         {  
  3.             string sendString = null;//要发送的字符串  
  4.             byte[] sendData = null;//要发送的字节数组  
  5.             UdpClient client = null;  
  6.   
  7.             IPAddress remoteIP = IPAddress.Parse("127.0.0.1");  
  8.             int remotePort = 11000;  
  9.             IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点  
  10.   
  11.             while (true)  
  12.             {  
  13.                 sendString = Console.ReadLine();  
  14.                 sendData = Encoding.Default.GetBytes(sendString);  
  15.   
  16.                 client = new UdpClient();  
  17.                 client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点  
  18.                 client.Close();//关闭连接  
  19.             }  
  20.         }  

原文地址:https://www.cnblogs.com/gc2013/p/3833373.html