赞
踩
在C#中使用UDP进行开发,你可以使用System.Net.Sockets
命名空间下的UdpClient
类。以下是一个简单的UDP发送和接收消息的例子:
UDP发送消息:
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
- public class UdpSend
- {
- public static void Main()
- {
- try
- {
- // 创建UdpClient实例
- UdpClient udpClient = new UdpClient();
-
- // 要发送的消息
- string message = "Hello, UDP Server!";
- byte[] data = Encoding.UTF8.GetBytes(message);
-
- // 服务器IP地址和端口
- IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
-
- // 发送消息
- udpClient.Send(data, data.Length, endPoint);
- Console.WriteLine("Message sent to the server.");
-
- // 关闭UdpClient
- udpClient.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- }
UDP接收消息:
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
-
- public class UdpReceive
- {
- public static void Main()
- {
- try
- {
- // 创建UdpClient实例,指定监听的端口
- UdpClient udpClient = new UdpClient(11000);
-
- // 接收消息
- IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
- byte[] data = udpClient.Receive(ref RemoteIpEndPoint);
-
- // 解码消息
- string message = Encoding.UTF8.GetString(data);
- Console.WriteLine("Message received: {0}", message);
-
- // 关闭UdpClient
- udpClient.Close();
- }
- catch (Exception e)
- {
- Console.WriteLine(e.ToString());
- }
- }
- }
在这个例子中,发送方创建了一个UdpClient
实例,然后将消息编码并发送到指定的服务器IP地址和端口。接收方同样创建了一个UdpClient
实例,监听指定的端口,并在有消息到达时接收和解码消息。
确保在运行这些程序之前,UDP服务器正在监听相应的端口,否则发送方可能会抛出异常。此外,如果你需要处理并发连接或者是大量数据的传输,你可能需要使用异步方法或者调整超时设置等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。