.NET Library Documentation

Socket.ReceiveFromAsync Method

Asynchronously receives data from a remote device and stores the data in the specified buffer.

public Task<int> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)

Parameters

Name Description
buffer An ArraySegment<Byte> object that specifies the location of the data to be received.
socketFlags A bitwise combination of the SocketFlags values that specify how the receive operation is to be performed.
remoteEndPoint An EndPoint object that specifies the remote device from which to receive data.

Return Value

A Task<Int32> object that represents the asynchronous operation. The value of the TResult parameter of the returned task is the number of bytes received.

Remarks

The ReceiveFromAsync method starts an asynchronous operation to receive data from a remote device. The method returns before the receive operation is complete. To process the data when it becomes available, use the methods provided by the Task<TResult> object returned by this method.

This method is used to receive datagrams from a connectionless socket. The remoteEndPoint parameter is updated to contain the endpoint of the sender.

Tip: For connection-oriented sockets, use the ReceiveAsync method.

Exceptions

Exception Type Condition
ObjectDisposedException The Socket has been closed.
SocketException An operating system error occurred while accessing the Socket.

Example

The following example demonstrates how to use the ReceiveFromAsync method to asynchronously receive data from a UDP socket.


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class Example
{
    public static async Task ReceiveDataAsync(int port)
    {
        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
            socket.Bind(localEndPoint);

            Console.WriteLine($"Listening on UDP port {port}...");

            byte[] buffer = new byte[1024];
            ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(buffer);
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

            try
            {
                SocketReceiveFromResult result = await socket.ReceiveFromAsync(receiveBuffer, SocketFlags.None, remoteEndPoint);

                string receivedMessage = Encoding.ASCII.GetString(buffer, 0, result.ReceivedBytes);
                Console.WriteLine($"Received {result.ReceivedBytes} bytes from {result.RemoteEndPoint}: {receivedMessage}");

                // Optionally send a response back
                byte[] responseData = Encoding.ASCII.GetBytes("Message received!");
                await socket.SendToAsync(new ArraySegment<byte>(responseData), SocketFlags.None, result.RemoteEndPoint);
            }
            catch (SocketException ex)
            {
                Console.WriteLine($"Socket error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"General error: {ex.Message}");
            }
        }
    }

    public static async Task Main(string[] args)
    {
        int udpPort = 11000;
        await ReceiveDataAsync(udpPort);
    }
}
        

See Also