Compartir vía


UdpClient.BeginReceive(AsyncCallback, Object) Método

Definición

Recibe un datagrama de un host remoto de forma asincrónica.

public:
 IAsyncResult ^ BeginReceive(AsyncCallback ^ requestCallback, System::Object ^ state);
public IAsyncResult BeginReceive (AsyncCallback? requestCallback, object? state);
public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state);
member this.BeginReceive : AsyncCallback * obj -> IAsyncResult
Public Function BeginReceive (requestCallback As AsyncCallback, state As Object) As IAsyncResult

Parámetros

requestCallback
AsyncCallback

Delegado de AsyncCallback que hace referencia al método que se invocará cuando la operación se complete.

state
Object

Objeto definido por el usuario que contiene información sobre la operación de recepción. Este objeto se pasa al delegado de requestCallback cuando la operación se completa.

Devoluciones

Objeto IAsyncResult que hace referencia a la recepción asincrónica.

Ejemplos

En el ejemplo de código siguiente se usa BeginReceive para recibir de forma asincrónica una respuesta del servidor.

private:
    static int listenPort = 13000;

public:
    value struct UdpState
    {
    public:
        UdpClient^ udpClient;
        IPEndPoint^ ipEndPoint;
    };

    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);
        }
    }
public struct UdpState
{
    public UdpClient u;
    public IPEndPoint e;
}

public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
    UdpClient u = ((UdpState)(ar.AsyncState)).u;
    IPEndPoint e = ((UdpState)(ar.AsyncState)).e;

    byte[] receiveBytes = u.EndReceive(ar, ref e);
    string receiveString = Encoding.ASCII.GetString(receiveBytes);

    Console.WriteLine($"Received: {receiveString}");
    messageReceived = true;
}

public static void ReceiveMessages()
{
    // Receive a message and write it to the console.
    IPEndPoint e = new IPEndPoint(IPAddress.Any, s_listenPort);
    UdpClient u = new UdpClient(e);

    UdpState s = new UdpState();
    s.e = e;
    s.u = u;

    Console.WriteLine("listening for messages");
    u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

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

Comentarios

La operación asincrónica BeginReceive debe completarse llamando al EndReceive método . Normalmente, el delegado invoca el requestCallback método .

Este método no se bloquea hasta que se complete la operación. Para bloquear hasta que se complete la operación, use el Receive método .

Para obtener información detallada sobre el uso del modelo de programación asincrónica, vea Llamar a métodos sincrónicos de forma asincrónica.

Se aplica a