Skip to content

TcpClient.GetStream() sample code is incorrect and confusing #63154

@geoffkizer

Description

@geoffkizer

See https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.getstream?view=net-6.0

There are several issues here:

(1) The sample incorrectly states twice that "Closing the tcpClient instance does not close the network stream." This is wrong: closing the TcpClient does in fact close the NetworkStream. The TcpClient.Close docs are clear about this.
(2) The sample calls GetStream() without having established the connection first. This will always fail.
(3) The sample explicitly tests for CanRead and CanWrite, but these will always be true on an established connection, so checking for these is very confusing.
(4) The sample explicitly closes the TcpClient in failure cases but not in the success case. This is bizarre and makes it unclear whether the user needs to call TcpClient.Close in general or not.
(5) The sample uses tcpClient.ReceiveBufferSize as the size of the user's allocated buffer for Receive. This seems to imply that this is good practice or even required; it is neither. TcpClient.ReceiveBufferSize configures the kernel buffer size for the socket and doesn't really have anything to do with the choice of user buffer size on Receive.

Additionally, the sample should be updated to use Span and using/IDisposable as any modern code would do.

If someone can tell me how to update the sample myself, I'd be happy to do so.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions