当前位置:   article > 正文

C#UDP服务器端和客户端连接_c# udp服务端

c# udp服务端

UDP客户端

  1. Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  2. IPAddress iPAddress = new IPAddress(new byte[] { 192, 168, 1, 20 });
  3. IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 5000);
  4. byte[] data = Encoding.UTF8.GetBytes("客户端上线了");
  5. EndPoint EP = (EndPoint)iPEndPoint;
  6. udpClient.SendTo(data, EP);

UDP服务端

  1. Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
  2. ProtocolType.Udp);
  3. IPAddress ipAddress = new IPAddress(new byte[] { 192, 168, 1, 20 });
  4. IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 5000);
  5. udpServer.Bind(ipEndPoint);
  6. IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
  7. EndPoint EP= (EndPoint)ipep;
  8. byte[] data = new byte[1024];
  9. int length = udpServer.ReceiveFrom(data, ref EP);
  10. Console.WriteLine("接收到的数据:" + Encoding.UTF8.GetString(data, 0, length));
  11. udpServer.Close();

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/895535
推荐阅读
相关标签
  

闽ICP备14008679号