Class UdpClientAsyncExtensions
Provides extension methods for the UdpClient class to enable asynchronous operations.
Namespace
System.Net.Sockets
Assembly
System.Net.Sockets.dll
Syntax
public static class UdpClientAsyncExtensions
Methods
ReceiveAsync
Asynchronously receives a datagram from the UdpClient.
public static Task<UdpReceiveResult> ReceiveAsync(this UdpClient udpClient)
Parameters
| Name | Type | Description |
|---|---|---|
udpClient |
UdpClient |
The UdpClient instance to receive from. |
Return Value
A Task<UdpReceiveResult> representing the asynchronous operation.
SendAsync
Asynchronously sends a datagram to a specified remote host.
public static Task<int> SendAsync(this UdpClient udpClient, byte[] datagram, int bytes, IPEndPoint endPoint)
Parameters
| Name | Type | Description |
|---|---|---|
udpClient |
UdpClient |
The UdpClient instance to send from. |
datagram |
byte[] |
The data to send. |
bytes |
int | The number of bytes to send. |
endPoint |
IPEndPoint | The endpoint to send the datagram to. |
Return Value
A Task<int> representing the asynchronous operation, with the number of bytes sent.
Remarks
The UdpClientAsyncExtensions class provides a convenient way to perform asynchronous network operations with UdpClient. These extension methods wrap the underlying asynchronous I/O operations, allowing you to write non-blocking code more easily.
Key methods include:
ReceiveAsync: For receiving data without blocking the calling thread.SendAsync: For sending data without blocking the calling thread.
These methods are crucial for building responsive network applications, especially in scenarios involving user interfaces or high concurrency.
Example
Sending and Receiving Data Asynchronously
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class UdpExample
{
public static async Task RunUdpClientAsync()
{
using var udpClient = new UdpClient(11000); // Listen on port 11000
var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, 11001);
var dataToSend = Encoding.ASCII.GetBytes("Hello from UDP client!");
// Send data
int bytesSent = await udpClient.SendAsync(dataToSend, dataToSend.Length, remoteEndPoint);
Console.WriteLine($"Sent {bytesSent} bytes.");
// Receive data (simulated receiver on port 11001)
var receiveTask = Task.Run(async () =>
{
using var receiverClient = new UdpClient(11001);
Console.WriteLine("Receiver listening on port 11001...");
var receivedResult = await receiverClient.ReceiveAsync();
var receivedData = Encoding.ASCII.GetString(receivedResult.Buffer, 0, receivedResult.BytesTransferred);
Console.WriteLine($"Received: {receivedData} from {receivedResult.RemoteEndPoint}");
});
await Task.Delay(new TimeSpan(0,0,1)); // Give receiver time to start
await receiveTask;
}
}