UdpClient.Receive Method

Receives a datagram from the UdpClient.

Important: This method blocks until a datagram is received.

Syntax

public byte[] Receive (ref System.Net.EndPoint remoteEP);

Parameters

Name Type Description
remoteEP System.Net.EndPoint System.Net.IPEndPoint that contains the port and address of the remote host.

Returns

A byte array containing the data received.

Exceptions

Type Condition
System.Net.Sockets.SocketException An error occurred while accessing the socket. See SocketError enumeration for detailed error information.
System.ObjectDisposedException The UdpClient has been disposed.

Remarks

The Receive method reads datagrams from the UdpClient. If no datagram is available, the Receive method blocks until a datagram is received.

The remoteEP parameter is an output parameter that is updated with the IPEndPoint of the sender.

You can use the ReceiveAsync method to receive datagrams asynchronously.

Note: The maximum size of a UDP datagram is 65,507 bytes.

Example

The following example demonstrates how to create a UdpClient, bind it to a local endpoint, and then receive data.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class UdpReceiver
{
    public static void Main(string[] args)
    {
        int port = 11000;
        UdpClient udpListener = null;
        try
        {
            // Create a UdpClient to listen on a specific port.
            udpListener = new UdpClient(port);

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

            // Create an IPEndPoint to store the sender's endpoint.
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

            // Listen for incoming datagrams.
            while (true)
            {
                // Receive data and the sender's endpoint.
                byte[] receivedBytes = udpListener.Receive(ref remoteEP);

                // Convert the bytes to a string.
                string receivedData = Encoding.ASCII.GetString(receivedBytes);

                Console.WriteLine($"Received '{receivedData}' from {remoteEP.Address}:{remoteEP.Port}");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
        finally
        {
            udpListener?.Close();
        }
    }
}