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参数必须包含已连接或默认Socket正用于通信。To 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方法通过state参数。Pass 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. 当你想要继续执行的原始线程时请在回调方法调用 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,则必须显式将绑定Socket到本地终结点使用Bind方法,或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太多的是,且引发的消息与SocketExceptionIf 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参数设置为IPIPv6根据需要,optionName参数设置为PacketInformation,并optionValue参数来启用此选项之前,调用BeginReceiveFrom方法。To 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方法之前建立或接受的连接时,你将获取SocketExceptionIf 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.

适用于

另请参阅