語言

UdpClient.EndReceive(IAsyncResult, IPEndPoint) 方法

定義

結束一個待處理的非同步接收。

public:
 cli::array <System::Byte> ^ EndReceive(IAsyncResult ^ asyncResult, System::Net::IPEndPoint ^ % remoteEP);
public byte[] EndReceive(IAsyncResult asyncResult, ref System.Net.IPEndPoint? remoteEP);
public byte[] EndReceive(IAsyncResult asyncResult, ref System.Net.IPEndPoint remoteEP);
member this.EndReceive : IAsyncResult * IPEndPoint -> byte[]
Public Function EndReceive (asyncResult As IAsyncResult, ByRef remoteEP As IPEndPoint) As Byte()

參數

asyncResult
IAsyncResult

IAsyncResult一個物件,透過呼叫 返回BeginReceive(AsyncCallback, Object)。

remoteEP
IPEndPoint

指定的遠端端點。

傳回

Byte[]

若成功,則會產生包含資料報資料的位元組陣列。

例外狀況

asyncResult 是 null。

asyncResult 呼叫方法時未回傳 BeginReceive(AsyncCallback, Object) 。

嘗試存取底層 Socket。

標的 Socket 資產已經關閉。

範例

以下程式碼範例用於 BeginSend 完成伺服器回應的非同步接收。

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

備註

此方法會阻塞直到操作完成。

要同步執行此操作,請使用該 Receive 方法。

適用於