Socket.EndReceiveFrom 方法

结束挂起的、从特定终结点进行异步读取。

**命名空间:**System.Net.Sockets
**程序集:**System(在 system.dll 中)

语法

声明
Public Function EndReceiveFrom ( _
    asyncResult As IAsyncResult, _
    ByRef endPoint As EndPoint _
) As Integer
用法
Dim instance As Socket
Dim asyncResult As IAsyncResult
Dim endPoint As EndPoint
Dim returnValue As Integer

returnValue = instance.EndReceiveFrom(asyncResult, endPoint)
public int EndReceiveFrom (
    IAsyncResult asyncResult,
    ref EndPoint endPoint
)
public:
int EndReceiveFrom (
    IAsyncResult^ asyncResult, 
    EndPoint^% endPoint
)
public int EndReceiveFrom (
    IAsyncResult asyncResult, 
    /** @ref */ EndPoint endPoint
)
JScript 不支持通过引用传递值类型参数。

参数

  • asyncResult
    IAsyncResult,它存储此异步操作的状态信息以及所有用户定义数据。

返回值

如果成功,则返回已接收的字节数。如果不成功,则返回 0。

异常

异常类型 条件

ArgumentNullException

asyncResult 为 空引用(在 Visual Basic 中为 Nothing)。

ArgumentException

BeginReceiveFrom 方法调用未返回 asyncResult。

InvalidOperationException

先前曾为异步读取调用过 EndReceiveFrom

SocketException

试图访问套接字时发生错误。有关更多信息,请参见备注部分。

ObjectDisposedException

Socket 已关闭。

备注

EndReceiveFrom 方法完成在 BeginReceiveFrom 方法中启动的异步读取操作。

在调用 BeginReceiveFrom 之前,需创建一个实现 AsyncCallback 委托的回调方法。该回调方法在单独的线程中执行并在 BeginReceiveFrom 返回后由系统调用。回调方法必须接受 BeginReceiveFrom 方法所返回的 IAsyncResult 作为参数。

在回调方法中,调用 IAsyncResultAsyncState 方法以获取传递给 BeginReceiveFrom 方法的状态对象。从该状态对象提取接收 Socket。在获取 Socket 之后,可以调用 EndReceiveFrom 方法以成功完成读取操作,并返回已读取的字节数。

EndReceiveFrom 方法将一直阻止到有数据可用为止。如果您使用的是无连接协议,则 EndReceiveFrom 将读取传入网络缓冲区中第一个排队的可用数据报。如果您使用的是面向连接的协议,则 EndReceiveFrom 方法将读取尽可能多的可用数据,直到达到 BeginReceiveFrom 方法的 size 参数所指定的字节数为止。如果远程主机使用 Shutdown 方法关闭了 Socket 连接,并且所有可用数据均已收到,则 EndReceiveFrom 方法将立即完成并返回零字节。若要获取接收到的数据,则调用 IAsyncResult 对象的 AsyncState 方法,然后提取生成的状态对象中所包含的缓冲区。若要标识发出方主机,请提取 EndPoint 并将其强制转换为 IPEndPoint。使用 IPEndPoint.Address 方法可获得 IP 地址,使用 IPEndPoint.Port 方法可以获得端口号。

提示

如果收到 SocketException,请使用 SocketException.ErrorCode 属性获取特定的错误代码。获取此代码后,您可以参考 MSDN Library 中的 Windows Sockets 第 2 版 API 错误代码文档,获取有关该错误的详细说明。

提示

当在应用程序中启用网络跟踪功能后,此成员将输出跟踪信息。有关更多信息,请参见 网络跟踪

示例

下面的代码示例结束一个挂起的、从特定 EndPoint 进行的异步读取。

   Dim so As StateObject = CType(ar.AsyncState, StateObject)
   Dim s As Socket = so.workSocket
   
   ' Creates a temporary EndPoint to pass to EndReceiveFrom.
   Dim sender As New IPEndPoint(IPAddress.Any, 0)
   Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
   
   Dim read As Integer = s.EndReceiveFrom(ar, tempRemoteEP)
   
   
   If read > 0 Then
      so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read))
      s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE, 0, tempRemoteEP, New AsyncCallback(AddressOf Async_Send_Receive.ReceiveFrom_Callback), so)
   Else
      If so.sb.Length > 1 Then
         'All the data has been read, so displays it to the console.
         Dim strContent As String
         strContent = so.sb.ToString()
         Console.WriteLine([String].Format("Read {0} byte from socket" + "data = {1} ", strContent.Length, strContent))
      End If
      s.Close()
   End If 
End Sub 'ReceiveFrom_Callback
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket;

   // Creates a temporary EndPoint to pass to EndReceiveFrom.
   IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;

   int read = s.EndReceiveFrom(ar, ref tempRemoteEP); 


if (read > 0) {
        so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
        s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE, 0, ref tempRemoteEP,
                                 new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so);
}
else{
     if (so.sb.Length > 1) {
          //All the data has been read, so displays it to the console.
          string strContent;
          strContent = so.sb.ToString();
          Console.WriteLine(String.Format("Read {0} byte from socket" + 
                             "data = {1} ", strContent.Length, strContent));
     }
     s.Close();
     
}
StateObject^ so = safe_cast<StateObject^>(ar->AsyncState);
Socket^ s = so->workSocket;

// Creates a temporary EndPoint to pass to EndReceiveFrom.
IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any,0 );
EndPoint^ tempRemoteEP = safe_cast<EndPoint^>(sender);

int read = s->EndReceiveFrom( ar, tempRemoteEP );

if ( read > 0 )
{
   so->sb->Append( Encoding::ASCII->GetString( so->buffer, 0, read ) );
   s->BeginReceiveFrom( so->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None,
      tempRemoteEP, gcnew AsyncCallback( &Async_Send_Receive::ReceiveFrom_Callback ), so );
}
else
{
   if ( so->sb->Length > 1 )
   {
      //All the data has been read, so displays it to the console.
      String^ strContent = so->sb->ToString();
      Console::WriteLine( "Read {0} byte from socket" +
         " data = {1}", strContent->Length, strContent );
   }
   s->Close();
}
StateObject so = (StateObject)ar.get_AsyncState();
Socket s = so.workSocket;
// Creates a temporary EndPoint to pass to EndReceiveFrom.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;
int read = s.EndReceiveFrom(ar, tempRemoteEP);

if (read > 0) {
    so.sb.Append(Encoding.get_ASCII().GetString(so.buffer, 0, read));
    s.BeginReceiveFrom(so.buffer, 0, StateObject.BUFFER_SIZE,
        (SocketFlags)0, tempRemoteEP,
        new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so);
}
else {
    if (so.sb.get_Length() > 1) {
        //All the data has been read, so displays it to the console.
        String strContent;
        strContent = so.sb.ToString();
        Console.WriteLine(String.Format("Read {0} byte from socket"
            + "data = {1} ", (Int32)(strContent.get_Length()),
            strContent));
    }
    s.Close();
}

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

Socket 类
Socket 成员
System.Net.Sockets 命名空间