UdpClient.ReceiveAsync Method
Declaration
public Task<byte[]> ReceiveAsync();
Parameters
This method does not take any parameters.
Returns
A Task<byte[]> that represents the asynchronous operation. The result of the task is a byte array containing the received datagram.
Exceptions
ObjectDisposedException: TheUdpClienthas been disposed.SocketException: A Windows Sockets error occurred while accessing theUdpClient.InvalidOperationException: TheUdpClientis not bound.
Remarks
The ReceiveAsync method is used to receive datagrams asynchronously. This method does not block the calling thread, allowing your application to continue processing other operations while waiting for data. The returned Task<byte[]> will complete when a datagram is received.
To use this method, you must first bind the UdpClient to a local port using UdpClient.Client.Bind() or by specifying an endpoint when creating the UdpClient instance. If the UdpClient is connected to a specific remote host, ReceiveAsync will only receive datagrams from that host.
The received data is returned as a byte array. The size of the buffer for receiving data can be controlled using the Socket.ReceiveBufferSize property of the underlying socket.
For an example of how to use ReceiveAsync, see the UdpClient.SendAsync method documentation.
Example
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class UdpReceiver
{
public static async Task ReceiveDataAsync(int port)
{
using (UdpClient receiver = new UdpClient(port))
{
Console.WriteLine($"Listening on port {port}...");
try
{
while (true)
{
// ReceiveAsync waits for a datagram and returns a UdpReceiveResult
UdpReceiveResult result = await receiver.ReceiveAsync();
string receivedMessage = Encoding.ASCII.GetString(result.Buffer);
IPEndPoint remoteEndPoint = result.RemoteEndPoint;
Console.WriteLine($"Received '{receivedMessage}' from {remoteEndPoint.Address}:{remoteEndPoint.Port}");
// Optional: Send a response back
byte[] responseData = Encoding.ASCII.GetBytes("Message received!");
await receiver.SendAsync(responseData, responseData.Length, remoteEndPoint);
}
}
catch (SocketException e)
{
Console.WriteLine($"SocketException: {e}");
}
catch (ObjectDisposedException e)
{
Console.WriteLine($"ObjectDisposedException: {e}");
}
finally
{
Console.WriteLine("Receiver stopped.");
}
}
}
public static async Task Main(string[] args)
{
int listenPort = 11000; // Example port
await ReceiveDataAsync(listenPort);
}
}