Socket.BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Method

定义

开始从指定网络设备中异步接收数据。Begins to asynchronously receive data from a specified network device.

public:
 IAsyncResult ^ BeginReceiveFrom(cli::array <System::Byte> ^ buffer, int offset, int size, System::Net::Sockets::SocketFlags socket_flags, System::Net::EndPoint ^ % remote_end, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socket_flags, ref System.Net.EndPoint remote_end, AsyncCallback callback, object state);
member this.BeginReceiveFrom : byte[] * int * int * System.Net.Sockets.SocketFlags *  * AsyncCallback * obj -> IAsyncResult
Public Function BeginReceiveFrom (buffer As Byte(), offset As Integer, size As Integer, socket_flags As SocketFlags, ByRef remote_end As EndPoint, callback As AsyncCallback, state As Object) As IAsyncResult

参数

buffer
Byte[]

Byte 类型的数组,它是存储接收到的数据的位置。An array of type Byte that is the storage location for the received data.

offset
Int32 Int32 Int32 Int32

buffer 参数中存储数据的位置,该位置从零开始计数。The zero-based position in the buffer parameter at which to store the data.

size
Int32 Int32 Int32 Int32

要接收的字节数。The number of bytes to receive.

socketFlags
SocketFlags SocketFlags SocketFlags SocketFlags

SocketFlags 值的按位组合。A bitwise combination of the SocketFlags values.

remoteEP
EndPoint EndPoint EndPoint EndPoint

一个 EndPoint,它表示数据的来源。An EndPoint that represents the source of the data.

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

引用异步读的 IAsyncResultAn IAsyncResult that references the asynchronous read.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

offset 小于 0。offset is less than 0.

-or- offset 大于 buffer 的长度。offset is greater than the length of buffer.

-or- size 小于 0。size is less than 0.

- 或 --or- size 大于 buffer 的长度减去 offset 参数的值。size is greater than the length of buffer minus the value of the offset parameter.

调用堆栈中的较高调用方无权执行所请求的操作。A caller higher in the call stack does not have permission for the requested operation.

示例

下面的代码示例从远程主机异步接收无连接的数据报。The following code example asynchronously receives connectionless datagrams from a remote host.

IPHostEntry^ lipa = Dns::Resolve( "host.contoso.com" );
IPEndPoint^ lep = gcnew IPEndPoint( lipa->AddressList[ 0 ], 11000);

      Socket^ s = gcnew Socket( lep->Address->AddressFamily,
      	  SocketType::Dgram,
         ProtocolType::Udp);
      
      IPEndPoint^ sender = gcnew IPEndPoint( IPAddress::Any, 0 );
      EndPoint^ tempRemoteEP = (EndPoint^)( sender );
      s->Connect( sender );
      
      try{
         while(true){
            allDone->Reset();
            StateObject^ so2 = gcnew StateObject();
                so2->workSocket = s;
                Console::WriteLine( "Attempting to Receive data from host.contoso.com" );
            
                s->BeginReceiveFrom( so2->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None, tempRemoteEP,
            gcnew AsyncCallback( &Async_Send_Receive::ReceiveFrom_Callback), so2);	
                allDone->WaitOne();
           }
      }
      catch ( Exception^ e )
      {
           Console::WriteLine( e );
      }
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

      Socket s = new Socket(lep.Address.AddressFamily,
      	                           SocketType.Dgram,
                                        ProtocolType.Udp);
      
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint tempRemoteEP = (EndPoint)sender;
      s.Connect(sender);
      
      try{
           while(true){
                allDone.Reset();
                StateObject so2 = new StateObject();
                so2.workSocket = s;
                Console.WriteLine("Attempting to Receive data from host.contoso.com");
            
                s.BeginReceiveFrom(so2.buffer, 0, StateObject.BUFFER_SIZE,0, ref tempRemoteEP,
                                   new AsyncCallback(Async_Send_Receive.ReceiveFrom_Callback), so2);	
                allDone.WaitOne();
           }
      }
      catch (Exception e){
           Console.WriteLine(e.ToString());
      }
   Dim lipa As IPHostEntry = Dns.Resolve("host.contoso.com")
   Dim lep As New IPEndPoint(lipa.AddressList(0), 11000)
   
   Dim s As New Socket(lep.Address.AddressFamily, SocketType.DGram, ProtocolType.Udp)
   
   Dim sender As New IPEndPoint(IPAddress.Any, 0)
   Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)
   s.Connect(sender)
   Try
      While True
         allDone.Reset()
         Dim so2 As New StateObject()
         so2.workSocket = s
         Console.WriteLine("Attempting to Receive data from host.contoso.com")
         
         s.BeginReceiveFrom(so2.buffer, 0, StateObject.BUFFER_SIZE, 0, tempRemoteEP, New AsyncCallback(AddressOf Async_Send_Receive.ReceiveFrom_Callback), so2)
         allDone.WaitOne()
      End While
   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try
End Sub 'ReceiveFrom

注解

BeginReceiveFrom方法从远程主机异步读取无连接的数据报。The BeginReceiveFrom method starts asynchronously reading connectionless datagrams from a remote host. BeginReceiveFrom调用方法使你能够在单独的执行线程中接收数据。Calling the BeginReceiveFrom method gives you the ability to receive data within a separate execution thread.

你可以创建一个实现AsyncCallback委托的回调方法, 并将其名称传递BeginReceiveFrom给方法。You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginReceiveFrom method. 为此, 你state的参数至少必须包含用于通信的已连接或默认值。 SocketTo do this, at the very minimum, your state parameter must contain the connected or default Socket being used for communication. 如果回调需要更多的信息, 可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 通过参数将此类的一个实例BeginReceiveFrom传递给方法。 statePass an instance of this class to the BeginReceiveFrom method through the state parameter.

回调方法应调用EndReceiveFrom方法。Your callback method should invoke the EndReceiveFrom method. 当应用程序调用BeginReceiveFrom时, 系统将使用一个单独的线程来执行指定的回调方法, 并且它将在EndReceiveFrom Socket读取数据或引发异常之前阻塞。When your application calls BeginReceiveFrom, the system will use a separate thread to execute the specified callback method, and it will block on EndReceiveFrom until the Socket reads data or throws an exception. 如果希望在调用BeginReceiveFrom方法后原始线程会被阻止, 请使用。 WaitHandle.WaitOneIf you want the original thread to block after you call the BeginReceiveFrom method, use WaitHandle.WaitOne. 如果希望原始线程继续执行, 请在回调方法中的 T:System.Threading.ManualResetEvent 上调用 Set 方法。Call the Set method on a T:System.Threading.ManualResetEvent in the callback method when you want the original thread to continue executing. 有关编写回调方法的其他信息, 请参阅将委托作为回调方法进行封送处理For additional information on writing callback methods, see Marshaling a Delegate as a Callback Method.

备注

在调用BeginReceiveFrom之前, 必须使用Bind方法将Socket显式绑定到本地终结点, 否则BeginReceiveFrom将引发SocketExceptionBefore calling BeginReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method, or BeginReceiveFrom will throw a SocketException.

此方法将buffer数据读入参数, 并捕获从其发送数据的远程主机终结点。This method reads data into the buffer parameter, and captures the remote host endpoint from which the data is sent. 有关如何检索此终结点的信息, 请参阅EndReceiveFromFor information on how to retrieve this endpoint, refer to EndReceiveFrom. 如果打算从未知主机或多台主机异步接收无连接的数据报, 此方法非常有用。This method is most useful if you intend to asynchronously receive connectionless datagrams from an unknown host or multiple hosts. 在这些情况下BeginReceiveFrom , 将读取接收到本地网络缓冲区中的第一个排队数据报。In these cases, BeginReceiveFrom will read the first enqueued datagram received into the local network buffer. 如果接收的buffer数据报大于大小, 则该BeginReceiveFrom方法将尽可能多地填充buffer SocketException消息, 并引发。If the datagram you receive is larger than the size of buffer, the BeginReceiveFrom method will fill buffer with as much of the message as is possible, and throw a SocketException. 如果使用的是不可靠的协议, 则过量的数据将丢失。If you are using an unreliable protocol, the excess data will be lost. 如果你使用的是可靠协议, 则该服务提供程序将保留多余的数据, 并且你可以通过使用足够大BeginReceiveFrom的缓冲区调用方法来检索这些数据。If you are using a reliable protocol, the excess data will be retained by the service provider and you can retrieve it by calling the BeginReceiveFrom method with a large enough buffer.

为了保证始终返回远程主机终结点Socket , 应用程序应Bind使用SetSocketOption方法将显式绑定到本地终结点, 然后optionLevel调用方法, 并将参数设置为。 IP PacketInformation optionValue BeginReceiveFrom或者根据需要, 将参数设置为,并将参数设置为,以便在调用方法之前启用此选项。optionName IPv6To guarantee that the remote host endpoint is always returned, an application should explicitly bind the Socket to a local endpoint using the Bind method and then call the SetSocketOption method with the optionLevel parameter set to IP or IPv6 as appropriate, the optionName parameter set to PacketInformation, and the optionValue parameter to enable this option before calling the BeginReceiveFrom method. 否则, 如果发送方在接收方调用BeginReceiveFrom方法之前发送了大量的数据报, 则不会返回远程主机终结点。Otherwise, it is possible for the remote host endpoint to not be returned when the sender has sent a number of datagrams before the receiver has called the BeginReceiveFrom method.

尽管BeginReceiveFrom适用于无连接协议, 但你也可以使用面向连接的协议。Although BeginReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 如果选择这样做, 则必须先Connect通过调用 / BeginConnect方法建立远程主机连接, 或通过调用AcceptBeginAccept方法接受传入的连接请求。If you choose to do so, you must first either establish a remote host connection by calling the Connect / BeginConnect method or accept an incoming connection request by calling the Accept or BeginAccept method. 如果在建立或BeginReceiveFrom接受连接之前调用方法, 将会SocketException收到。If you call the BeginReceiveFrom method before establishing or accepting a connection, you will get a SocketException. 还可以在调用BeginReceiveFrom方法之前, 为无连接协议建立默认远程主机。You can also establish a default remote host for a connectionless protocol prior to calling the BeginReceiveFrom method. 在这两种情况下, BeginReceiveFrom方法将remoteEP忽略参数, 并仅从已连接或默认的远程主机接收数据。In either of these cases, the BeginReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

使用面向连接的套接字BeginReceiveFrom时, 将读取与size参数指定的字节数最多的可用数据。With connection-oriented sockets, BeginReceiveFrom will read as much data as is available up to the number of bytes specified by the size parameter.

若要取消挂起BeginReceiveFrom的, 请Close调用方法。To cancel a pending BeginReceiveFrom, call the Close method.

备注

如果收到SocketException, 请SocketException.ErrorCode使用属性获取特定的错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后, 请参阅Windows 套接字版本 2 API 错误代码文档, 以获取有关错误的详细说明。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息, 请参阅.NET Framework 中的网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步Socket方法缓存执行上下文 (安全上下文、模拟用户和调用上下文)。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 第一次使用特定的上下文 (特定的异步Socket方法、特定Socket的实例和特定的回调) 后, 该上下文的后续使用将会提高性能。After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

适用于

另请参阅