c# 实现简单udp数据的发送和接收

服务端代码

static void Main(string[] args) 

  UdpClient client = null; 
  string receiveString = null; 
  byte[] receiveData = null; 
  //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点 
  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("123.45.6.7"); //假设发送给这个IP
  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();//关闭连接 
  } 
}

猜你喜欢

转载自blog.csdn.net/mixiu888/article/details/80831390