Прочетете на английски Редактиране

Споделяне чрез


TcpClient.GetStream Method

Definition

Returns the NetworkStream used to send and receive data.

C#
public System.Net.Sockets.NetworkStream GetStream();

Returns

The underlying NetworkStream.

Exceptions

The TcpClient is not connected to a remote host.

The TcpClient has been closed.

Examples

The following code example uses GetStream to obtain the underlying NetworkStream. After obtaining the NetworkStream, it sends and receives using its Write and Read methods.

C#
using TcpClient tcpClient = new TcpClient();
tcpClient.ConnectAsync("contoso.com", 5000);

using NetworkStream netStream = tcpClient.GetStream();

// Send some data to the peer.
byte[] sendBuffer = Encoding.UTF8.GetBytes("Is anybody there?");
netStream.Write(sendBuffer);

// Receive some data from the peer.
byte[] receiveBuffer = new byte[1024];
int bytesReceived = netStream.Read(receiveBuffer);
string data = Encoding.UTF8.GetString(receiveBuffer.AsSpan(0, bytesReceived));

Console.WriteLine($"This is what the peer sent to you: {data}");

Remarks

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

You must call the Connect method first, or the GetStream method will throw an InvalidOperationException. After you have obtained the NetworkStream, call the Write method to send data to the remote host. Call the Read 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 DataAvailable property. A true value means that data has arrived from the remote host and is available for reading. In this case, Read is guaranteed to complete immediately. If the remote host has shutdown its connection, Read will immediately return with zero bytes.

Бележка

If you receive a 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 for a detailed description of the error.

Бележка

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

Applies to

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

See also