从远程主机异步接收数据报。

public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state);

参数

requestCallback
AsyncCallback

AsyncCallback 委托,它引用操作完成时要调用的方法。

state
Object

requestCallback 委托。

返回

IAsyncResult

IAsyncResult 对象,它引用异步接收。

示例

BeginReceive 异步接收服务器响应。

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);
    }
}

注解

通常,方法由 requestCallback 委托调用。

Receive 方法。

以异步方式调用同步方法。

适用于

.NET

5.0 RC2

.NET Core

3.1 3.0 2.2 2.1 2.0

.NET Framework

4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6 4.5.2 4.5.1 4.5 4.0 3.5 3.0 2.0

.NET Standard

2.1 2.0

Xamarin.Android

7.1

Xamarin.iOS

10.8

Xamarin.Mac

3.0

相关文章:

  • 2022-02-04
  • 2021-08-27
  • 2022-12-23
  • 2021-11-08
  • 2021-07-29
  • 2021-06-08
  • 2021-08-05
猜你喜欢
  • 2022-12-23
  • 2021-06-06
  • 2021-08-20
  • 2021-05-16
  • 2022-12-23
相关资源
相似解决方案