Export (0) Print
Expand All

Socket.EndReceive Method (IAsyncResult)

Ends a pending asynchronous read.

Namespace: System.Net.Sockets
Assembly: System (in system.dll)

public int EndReceive (
	IAsyncResult asyncResult
)
public int EndReceive (
	IAsyncResult asyncResult
)
public function EndReceive (
	asyncResult : IAsyncResult
) : int

Parameters

asyncResult

An IAsyncResult that stores state information and any user defined data for this asynchronous operation.

Return Value

The number of bytes received.

Exception typeCondition

ArgumentNullException

asyncResult is a null reference (Nothing in Visual Basic).

ArgumentException

asyncResult was not returned by a call to the BeginReceive method.

InvalidOperationException

EndReceive was previously called for the asynchronous read.

SocketException

An error occurred when attempting to access the socket. See the Remarks section for more information.

ObjectDisposedException

The Socket has been closed.

The EndReceive method completes the asynchronous read operation started in the BeginReceive method.

Before calling BeginReceive, you need to create a callback method that implements the AsyncCallback delegate. This callback method executes in a separate thread and is called by the system after BeginReceive returns. The callback method must accept the IAsyncResult returned by the BeginReceive method as a parameter.

Within the callback method, call the AsyncState method of the IAsyncResult to obtain the state object passed to the BeginReceive method. Extract the receiving Socket from this state object. After obtaining the Socket, you can call the EndReceive method to successfully complete the read operation and return the number of bytes read.

The EndReceive method will block until data is available. If you are using a connectionless protocol, EndReceive will read the first enqueued datagram available in the incoming network buffer. If you are using a connection-oriented protocol, the EndReceive method will read as much data as is available up to the number of bytes you specified in the size parameter of the BeginReceive method. If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the EndReceive method will complete immediately and return zero bytes.

To obtain the received data, call the AsyncState method of the IAsyncResult, and extract the buffer contained in the resulting state object.

To cancel a pending BeginReceive, call the Close method.

NoteNote

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 in the MSDN library for a detailed description of the error.

NoteNote

All I/O initiated by a given thread is canceled when that thread exits. A pending asynchronous operation can fail if the thread exits before the operation completes.

NoteNote

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing.

The following code example ends a pending asynchronous read. For a complete example that demonstrates asynchronous communications with sockets, see Socket Code Examples.

public static void Read_Callback(IAsyncResult ar){
	StateObject so = (StateObject) ar.AsyncState;
	Socket s = so.workSocket;

	int read = s.EndReceive(ar);

	if (read > 0) {
            so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
            s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, 
            	                     new AsyncCallback(Async_Send_Receive.Read_Callback), so);
	}
	else{
	     if (so.sb.Length > 1) {
	          //All of 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 = (StateObject)ar.get_AsyncState();
Socket s = so.workSocket;
int read = s.EndReceive(ar);

if (read > 0) {
    so.sb.Append(Encoding.get_ASCII().GetString(so.buffer, 0, read));
    s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE,
        (SocketFlags)0, new AsyncCallback(Async_Send_Receive.
        Read_Callback), so);
}
else {
    if (so.sb.get_Length() > 1) {
        //All of 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

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2015 Microsoft