UdpClient.EndReceive(IAsyncResult, IPEndPoint) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
结束挂起的异步接收。
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
调用 BeginReceive(AsyncCallback, Object) 后返回的 IAsyncResult 对象。
- remoteEP
- IPEndPoint
指定的远程终结点。
返回
Byte[]
如果成功,则返回包含数据报数据的字节数组。
例外
asyncResult
为 null
。
对 BeginReceive(AsyncCallback, Object) 方法的调用未返回 asyncResult
。
尝试访问基础 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 方法。