当前位置:   article > 正文

c# UDP 开发

c# UDP 开发

在C#中使用UDP进行开发,你可以使用System.Net.Sockets命名空间下的UdpClient类。以下是一个简单的UDP发送和接收消息的例子:

UDP发送消息:

  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. public class UdpSend
  6. {
  7. public static void Main()
  8. {
  9. try
  10. {
  11. // 创建UdpClient实例
  12. UdpClient udpClient = new UdpClient();
  13. // 要发送的消息
  14. string message = "Hello, UDP Server!";
  15. byte[] data = Encoding.UTF8.GetBytes(message);
  16. // 服务器IP地址和端口
  17. IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
  18. // 发送消息
  19. udpClient.Send(data, data.Length, endPoint);
  20. Console.WriteLine("Message sent to the server.");
  21. // 关闭UdpClient
  22. udpClient.Close();
  23. }
  24. catch (Exception e)
  25. {
  26. Console.WriteLine(e.ToString());
  27. }
  28. }
  29. }

UDP接收消息:

  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. public class UdpReceive
  6. {
  7. public static void Main()
  8. {
  9. try
  10. {
  11. // 创建UdpClient实例,指定监听的端口
  12. UdpClient udpClient = new UdpClient(11000);
  13. // 接收消息
  14. IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
  15. byte[] data = udpClient.Receive(ref RemoteIpEndPoint);
  16. // 解码消息
  17. string message = Encoding.UTF8.GetString(data);
  18. Console.WriteLine("Message received: {0}", message);
  19. // 关闭UdpClient
  20. udpClient.Close();
  21. }
  22. catch (Exception e)
  23. {
  24. Console.WriteLine(e.ToString());
  25. }
  26. }
  27. }

        在这个例子中,发送方创建了一个UdpClient实例,然后将消息编码并发送到指定的服务器IP地址和端口。接收方同样创建了一个UdpClient实例,监听指定的端口,并在有消息到达时接收和解码消息。

        确保在运行这些程序之前,UDP服务器正在监听相应的端口,否则发送方可能会抛出异常。此外,如果你需要处理并发连接或者是大量数据的传输,你可能需要使用异步方法或者调整超时设置等。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号