Socket.BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Method
Definition
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 socketFlags, System::Net::EndPoint ^ % remoteEP, AsyncCallback ^ callback, System::Object ^ state);
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 socketFlags, ref System.Net.EndPoint remoteEP, AsyncCallback? callback, object? state);
public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, AsyncCallback callback, 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 * EndPoint * AsyncCallback * obj -> IAsyncResult
member this.BeginReceiveFrom : byte[] * int * int * System.Net.Sockets.SocketFlags * EndPoint * AsyncCallback * obj -> IAsyncResult
Public Function BeginReceiveFrom (buffer As Byte(), offset As Integer, size As Integer, socketFlags As SocketFlags, ByRef remoteEP As EndPoint, callback As AsyncCallback, state As Object) As 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
Parameters
- offset
- Int32
The zero-based position in the buffer
parameter at which to store the data.
- size
- Int32
The number of bytes to receive.
- socketFlagssocket_flags
- SocketFlags
A bitwise combination of the SocketFlags values.
- callback
- AsyncCallback
The AsyncCallback delegate.
- state
- Object
An object that contains state information for this request.
Returns
An IAsyncResult that references the asynchronous read.
Exceptions
An error occurred when attempting to access the socket.
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.
The Socket has been closed.
A caller higher in the call stack does not have permission for the requested operation.
Examples
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
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 invoke 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 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.
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.
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. 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.
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.
To cancel a pending BeginReceiveFrom, call the Close method.
Note
If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.
Note
This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .NET Framework.
Note
The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 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.