以下是使用UdpClient的BeginReceive和Receive
As
ync方法接收数据的示例代码:
使用BeginReceive方法接收数据:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class UdpReceiveExample
private static UdpClient udpClient;
private static IPEndPoint ipEndPoint;
private static bool isRunning;
public static void Main()
udpClient = new UdpClient(1234);
ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
isRunning = true;
udpClient.BeginReceive(ReceiveCallback, null);
Console.WriteLine("Waiting for data...");
while (isRunning)
// Do other tasks while waiting for data
udpClient.Close();
private static void ReceiveCallback(IAsyncResult ar)
byte[] receivedBytes = udpClient.EndReceive(ar, ref ipEndPoint);
string receivedData = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Received data: " + receivedData);
// Continue listening for data
udpClient.BeginReceive(ReceiveCallback, null);
使用ReceiveAsync方法接收数据:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class UdpReceiveExample
private static UdpClient udpClient;
private static IPEndPoint ipEndPoint;
private static bool isRunning;
public static async Task Main()
udpClient = new UdpClient(1234);
ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
isRunning = true;
Console.WriteLine("Waiting for data...");
while (isRunning)
UdpReceiveResult result = await udpClient.ReceiveAsync();
byte[] receivedBytes = result.Buffer;
string receivedData = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine("Received data: " + receivedData);
udpClient.Close();
请注意,使用ReceiveAsync方法时,Main方法必须声明为async,并且使用await关键字等待接收操作完成。在循环中接收数据时,不需要调用BeginReceive或EndReceive方法,因为ReceiveAsync方法会自动处理接收操作。