This documentation is archived and is not being maintained.

NetworkStream.EndRead Method

Handles the end of an asynchronous read.

[Visual Basic]
Overrides Public Function EndRead( _
   ByVal asyncResult As IAsyncResult _
) As Integer
[C#]
public override int EndRead(
 IAsyncResult asyncResult
);
[C++]
public: int EndRead(
 IAsyncResult* asyncResult
);
[JScript]
public override function EndRead(
   asyncResult : IAsyncResult
) : int;

Parameters

asyncResult
An IAsyncResult representing an asynchronous call.

Return Value

The number of bytes read from the NetworkStream.

Exceptions

Exception Type Condition
ArgumentException asyncResult is a null reference (Nothing in Visual Basic).
IOException The underlying Socket is closed.

-or-

An error occurs while reading the network.

ObjectDisposedException The NetworkStream is closed.
IOException An error occurred when accessing the socket. See the Remarks section for more information.

Remarks

The EndRead method completes the asynchronous read operation started in the BeginRead method.

Before calling BeginRead, 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 BeginRead returns. The callback method must accept the IAsyncResult returned from the BeginRead method as a parameter.

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

The EndRead method will block until data is available. The EndRead method will read as much data as is available up to the number of bytes specified in the size parameter of the BeginRead method. If the remote host shuts down the Socket connection and all available data has been received, the EndRead 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.

Note   If you receive a IOException check the InnerException property to determine if it was caused by a SocketException. If so, use 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++] In the following example, myReadCallback is provided to BeginRead as the callback method. EndRead is implemented in myReadCallback to complete the asynchronous read call started by BeginRead.

[Visual Basic] 
Public Shared Sub myReadCallBack(ar As IAsyncResult)
   
   Dim myNetworkStream As NetworkStream = CType(ar.AsyncState, NetworkStream)
   Dim myReadBuffer(1024) As Byte
   Dim myCompleteMessage As [String] = ""
   Dim numberOfBytesRead As Integer
   
   numberOfBytesRead = myNetworkStream.EndRead(ar)
   myCompleteMessage = [String].Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead))
   
   ' message received may be larger than buffer size so loop through until you have it all.
   While myNetworkStream.DataAvailable
      
      myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, New AsyncCallback(AddressOf NetworkStream_ASync_Send_Receive.myReadCallBack), myNetworkStream)
   End While
   
   
   ' Print out the received message to the console.
   Console.WriteLine(("You received the following message : " + myCompleteMessage))
End Sub 'myReadCallBack

'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
   Main(System.Environment.GetCommandLineArgs())
End Sub



[C#] 

public static void myReadCallBack(IAsyncResult ar ){

    NetworkStream myNetworkStream = (NetworkStream)ar.AsyncState;
    byte[] myReadBuffer = new byte[1024];
    String myCompleteMessage = "";
    int numberOfBytesRead;

    numberOfBytesRead = myNetworkStream.EndRead(ar);
    myCompleteMessage = 
        String.Concat(myCompleteMessage, Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));    
    
    // message received may be larger than buffer size so loop through until you have it all.
    while(myNetworkStream.DataAvailable){
        
        myNetworkStream.BeginRead(myReadBuffer, 0, myReadBuffer.Length, 
                                                   new AsyncCallback(NetworkStream_ASync_Send_Receive.myReadCallBack), 
                                                   myNetworkStream);  

    }

    // Print out the received message to the console.
    Console.WriteLine("You received the following message : " +
                                myCompleteMessage);
}


[C++] 
static void myReadCallBack(IAsyncResult* ar) {
    NetworkStream* myNetworkStream = __try_cast<NetworkStream*>(ar->AsyncState);
    Byte myReadBuffer[] = new Byte[1024];
    String* myCompleteMessage = S"";
    int numberOfBytesRead;

    numberOfBytesRead = myNetworkStream->EndRead(ar);
    myCompleteMessage = 
        String::Concat(myCompleteMessage, Encoding::ASCII->GetString(myReadBuffer, 0, numberOfBytesRead));    

    // message received may be larger than buffer size so loop through until you have it all.
    while (myNetworkStream->DataAvailable) {
        AsyncCallback* pasync = new AsyncCallback(0, &myReadCallBack);
        myNetworkStream->BeginRead(myReadBuffer, 0, myReadBuffer->Length, 
            pasync, 
            myNetworkStream);  
    }

    // Print out the received message to the console.
    Console::WriteLine(S"You received the following message : {0}", myCompleteMessage);
}

[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

NetworkStream Class | NetworkStream Members | System.Net.Sockets Namespace | BeginRead | Including Asynchronous Calls

Show: