NetworkStream ns = client.GetStream(); // client object is a TcpClient instance byte[] buffer = new byte[1024]; ns.BeginRead(buffer, 0, buffer.Length, OnReadComplete, buffer); void OnReadComplete(IAsyncResult iar) { byte[] buffer = (byte[])iar.AsyncState; int bytesRead = ns.EndRead(iar); // process the bytesRead data ns.BeginRead(buffer, 0, buffer.Length, OnReadComplete, buffer); }
NetworkStream ns = client.GetStream(); // client object is a TcpClient instance byte[] buffer = new byte[1024]; IAsyncResult ar = ns.BeginRead(buffer, 0, buffer.Length, null, null); if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5))) { // timeout occurred } else { int bytesRead = ns.EndRead(ar); // process the bytesRead data }In this example, a NetworkStream object is obtained from a TcpClient instance. The BeginRead method is called on the NetworkStream, passing in a byte array buffer, the offset at which to begin writing data, and the maximum number of bytes to read. A null callback function and state object are also passed. The AsyncWaitHandle property of the IAsyncResult object returned by BeginRead is used to wait for the read to complete. If the read does not complete within five seconds, a timeout occurs and the code within the if statement is executed. Otherwise, the EndRead method is called to get the number of bytes read and the data is processed. Library: The package library used in these examples is System.Net.Sockets. This library provides the classes and methods necessary for network communication in C#.