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();//关闭连接
  }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM