UdpClient::EndReceive Method (IAsyncResult^, IPEndPoint^%)

 

Ends a pending asynchronous receive.

Namespace:   System.Net.Sockets
Assembly:  System (in System.dll)

public:
array<unsigned char>^ EndReceive(
	IAsyncResult^ asyncResult,
	IPEndPoint^% remoteEP
)

Parameters

asyncResult
Type: System::IAsyncResult^

An IAsyncResult object returned by a call to BeginReceive.

remoteEP
Type: System.Net::IPEndPoint^%

The specified remote endpoint.

Return Value

Type: array<System::Byte>^

If successful, the number of bytes received. If unsuccessful, this method returns 0.

Exception Condition
ArgumentNullException

asyncResult is null.

ArgumentException

asyncResult was not returned by a call to the BeginReceive method.

InvalidOperationException

EndReceive was previously called for the asynchronous read.

SocketException

An error occurred when attempting to access the underlying Socket. See the Remarks section for more information.

ObjectDisposedException

The underlying Socket has been closed.

This method blocks until the operation is complete.

To perform this operation synchronously, use the Receive method.

The following code example uses BeginSend to complete an asynchronous receive of a server response.

public:
    static bool isMessageReceived;

    static void ReceiveCallback(IAsyncResult^ asyncResult)
    {
        UdpClient^ udpClient =
            ((UdpState)(asyncResult->AsyncState)).udpClient;
        IPEndPoint^ ipEndPoint =
            ((UdpState)(asyncResult->AsyncState)).ipEndPoint;

        array<Byte>^ receiveBytes =
            udpClient->EndReceive(asyncResult, ipEndPoint);
        String^ receiveString =
            Encoding::ASCII->GetString(receiveBytes);

        Console::WriteLine("Received: {0}", receiveString);
        isMessageReceived = true;
    }

    static void ReceiveMessages()
    {
        // Receive a message and write it to the console.
        IPEndPoint^ ipEndPoint = gcnew IPEndPoint(IPAddress::Any, listenPort);
        UdpClient^ udpClient = gcnew UdpClient(ipEndPoint);

        UdpState^ udpState = gcnew UdpState();
        udpState->ipEndPoint = ipEndPoint;
        udpState->udpClient = udpClient;

        Console::WriteLine("listening for messages");
        udpClient->BeginReceive(gcnew AsyncCallback(ReceiveCallback),
            udpState);

        // Do some work while we wait for a message. For this example,
        // we'll just sleep
        while (!isMessageReceived)
        {
            Thread::Sleep(100);
        }
    }

.NET Framework
Available since 2.0
Return to top
Show: