UDP通信是无连接通信,客户端在发送数据前无需与服务器端建立连接,即使服务器端不在线也可以发送,但是不能保证服务器端可以收到数据。
服务器端代码:
- static void Main(string[] args)
- {
- UdpClient client = null;
- string receiveString = null;
- byte[] receiveData = null;
-
- IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
-
- while (true)
- {
- client = new UdpClient(11000);
- receiveData = client.Receive(ref remotePoint);
- receiveString = Encoding.Default.GetString(receiveData);
- Console.WriteLine(receiveString);
- client.Close();
- }
- }
客户端代码:
- static void Main(string[] args)
- {
- string sendString = null;
- byte[] sendData = null;
- UdpClient client = null;
-
- IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
- int remotePort = 11000;
- IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);
-
- while (true)
- {
- sendString = Console.ReadLine();
- sendData = Encoding.Default.GetBytes(sendString);
-
- client = new UdpClient();
- client.Send(sendData, sendData.Length, remotePoint);
- client.Close();
- }
- }
C#中使用UDP通信,布布扣,bubuko.com
C#中使用UDP通信
原文:http://www.cnblogs.com/gc2013/p/3833373.html