Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Socket.BeginReceiveFrom Method

Begins to asynchronously receive data from a specified network device.

[Visual Basic]
Public Function BeginReceiveFrom( _
   ByVal buffer() As Byte, _
   ByVal offset As Integer, _
   ByVal size As Integer, _
   ByVal socketFlags As SocketFlags, _
   ByRef remoteEP As EndPoint, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginReceiveFrom(
 byte[] buffer,
 int offset,
 int size,
 SocketFlags socketFlags,
   ref EndPoint remoteEP,
 AsyncCallback callback,
 object state
);
[C++]
public: IAsyncResult* BeginReceiveFrom(
 unsigned char buffer __gc[],
 int offset,
 int size,
 SocketFlags socketFlags,
   EndPoint** remoteEP,
 AsyncCallback* callback,
 Object* state
);
[JScript]
public function BeginReceiveFrom(
   buffer : Byte[],
 offset : int,
 size : int,
 socketFlags : SocketFlags,
 remoteEP : EndPoint,
 callback : AsyncCallback,
 state : Object
) : IAsyncResult;

Parameters

buffer
An array of type Byte that is the storage location for the received data.
offset
The zero-based position in the buffer parameter at which to store the data.
size
The number of bytes to receive.
socketFlags
A bitwise combination of the SocketFlags values.
remoteEP
An EndPoint that represents the source of the data.
callback
The AsyncCallback delegate.
state
An object containing state information for this request.

Return Value

An IAsyncResult that references the asynchronous read.

Exceptions

Exception Type Condition
ArgumentNullException buffer is a null reference (Nothing in Visual Basic).

-or-

remoteEP is a null reference (Nothing).

SocketException An error occurred when attempting to access the socket. See the Remarks section for more information.
ArgumentOutOfRangeException offset is less than 0.

-or-

offset is greater than the length of buffer.

-or-

size is less than 0.

-or-

size is greater than the length of buffer minus the value of the offset parameter.

ObjectDisposedException The Socket has been closed.
SecurityException A caller higher in the call stack does not have permission for the requested operation.

Remarks

The BeginReceiveFrom method starts asynchronously reading connectionless datagrams from a remote host. Calling the BeginReceiveFrom method gives you the ability to receive data within a separate execution thread.

You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginReceiveFrom method. To do this, at the very minimum, your state parameter must contain the connected or default Socket being used for communication. If your callback needs more information, you can create a small class to hold the Socket and the other required information. Pass an instance of this class to the BeginReceiveFrom method through the state parameter.

Your callback method should implement the EndReceiveFrom method. 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. If you want the original thread to block after you call the BeginReceiveFrom method, use WaitHandle.WaitOne. Call ManualResetEvent.Set in the callback method when you want the original thread to continue executing. For additional information on writing callback methods, see Callback Sample.

Note   Before calling BeginReceiveFrom, you must explicitly bind the Socket to a local endpoint using the Bind method, or BeginReceiveFrom will throw a SocketException.

This method reads data into the buffer parameter, and captures the remote host endpoint from which the data is sent. For 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. In these cases, BeginReceiveFrom will read the first enqueued datagram received into the local network buffer. 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. 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.

Although BeginReceiveFrom is intended for connectionless protocols, you can use a connection-oriented protocol as well. 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. If you call the BeginReceiveFrom method before establishing or accepting a connection, you will get a SocketException. You can also establish a default remote host for a connectionless protocol prior to calling the BeginReceiveFrom method. In either of these cases, the BeginReceiveFrom method will ignore the remoteEP parameter and only receive data from the connected or default remote host.

With connection-oriented sockets, BeginReceiveFrom will read as much data as is available up to the number of bytes specified by the size parameter.If you specify the OutOfBand flag as the socketFlags parameter and the Socket is configured for in-line reception of out-of-band (OOB) data (using OutOfBandInline) and OOB data is available, BeginReceiveFrom returns only OOB data. The OOB data is a logically independent transmission channel associated with each pair of connected stream sockets. This data is delivered with higher priority and independently of the normal data. If you specify the Peek flag as the socketFlags parameter, the available data is copied into the receive buffer but not removed from the system buffer.

Note   If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Socket Version 2 API error code documentation in MSDN for a detailed description of the error.

Example

[Visual Basic, C#, C++] The following example asynchronously receives connectionless datagrams from a remote host.

[Visual Basic] 
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.Stream, ProtocolType.Tcp)

Dim sender As New IPEndPoint(IPAddress.Any, 0)
Dim tempRemoteEP As EndPoint = CType(sender, EndPoint)

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

[C#] 
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

   Socket s = new Socket(lep.Address.AddressFamily,
                                  SocketType.Stream,
                                     ProtocolType.Tcp);
   
   IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)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());
   }

[C++] 
IPHostEntry* lipa = Dns::Resolve(S"host.contoso.com");
IPEndPoint* lep = new IPEndPoint(lipa->AddressList[0], 11000);

Socket* s = new Socket(lep->Address->AddressFamily,
    SocketType::Stream,
    ProtocolType::Tcp);

IPEndPoint* sender = new IPEndPoint(IPAddress::Any, 0);
EndPoint* tempRemoteEP = __try_cast<EndPoint*>(sender);

try {
    while (true) {
        allDone->Reset();
        StateObject* so2 = new StateObject();
        so2->workSocket = s;
        Console::WriteLine(S"Attempting to Receive data from host.contoso.com");

        s->BeginReceiveFrom(so2->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None, &tempRemoteEP,
            new AsyncCallback(0, &Async_Send_Receive::ReceiveFrom_Callback), so2);    
        allDone->WaitOne();
    }
} catch (Exception* e) {
    Console::WriteLine(e);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Socket Class | Socket Members | System.Net.Sockets Namespace | Including Asynchronous Calls | EndReceiveFrom | AsyncCallback | Callback Sample | Bind | Connect | Accept

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft