UdpClient::BeginReceive Method (AsyncCallback^, Object^)

 

Receives a datagram from a remote host asynchronously.

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

public:
[HostProtectionAttribute(SecurityAction::LinkDemand, ExternalThreading = true)]
IAsyncResult^ BeginReceive(
	AsyncCallback^ requestCallback,
	Object^ state
)

Parameters

requestCallback
Type: System::AsyncCallback^

An AsyncCallback delegate that references the method to invoke when the operation is complete.

state
Type: System::Object^

A user-defined object that contains information about the receive operation. This object is passed to the requestCallback delegate when the operation is complete.

Return Value

Type: System::IAsyncResult^

An IAsyncResult object that references the asynchronous receive.

The asynchronous BeginReceive operation must be completed by calling the EndReceive method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use the Receive method.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

The following code example uses BeginReceive to asynchronously receive 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: