System.Net.Sockets.TcpClient.GetStream Method

Returns the System.Net.Sockets.NetworkStream used to send and receive data.

Syntax

public NetworkStream GetStream ()

Returns

The underlying System.Net.Sockets.NetworkStream.

Remarks

TcpClient.GetStream returns a System.Net.Sockets.NetworkStream that you can use to send and receive data. The System.Net.Sockets.NetworkStream class inherits from the System.IO.Stream class, which provides a rich collection of methods and properties used to facilitate network communications.

You must call the TcpClient.Connect(string, int) method first, or the TcpClient.GetStream method will throw an InvalidOperationException. After you have obtained the System.Net.Sockets.NetworkStream, call the NetworkStream.Write(Byte[], int, int) method to send data to the remote host. Call the NetworkStream.Read(Byte[], int, int) method to receive data arriving from the remote host. Both of these methods block until the specified operation is performed. You can avoid blocking on a read operation by checking the NetworkStream.DataAvailable property. A true value means that data has arrived from the remote host and is available for reading. In this case, NetworkStream.Read(Byte[], int, int) is guaranteed to complete immediately. If the remote host has shutdown its connection, NetworkStream.Read(Byte[], int, int) will immediately return with zero bytes.

Note:

You must close the System.Net.Sockets.NetworkStream when you are through sending and receiving data. Closing System.Net.Sockets.TcpClient does not release the System.Net.Sockets.NetworkStream.

Note:

If you receive a System.Net.Sockets.SocketException, use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation in MSDN 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 [<topic://conUsingNetworkTracing>].

Requirements

Namespace: System.Net.Sockets
Assembly: System (in System.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0