The NetworkStream Class

If you need to transmit data across a network, chances are that you'll need to use the NetworStream class.
In this article we will show you how to obtain and to use an instance of the NetworkStream class.

The NetworkStream class derive from Stream, so it must implement all of the abstract methods that Stream exposes. The fact that NetworkStream derive from Stream allow you to handle the network communication just like you would handle writing and reading from a file.

Before using the NetworkStream, you will need to create a new instance. There are several ways to obtain such an instance:

  • By using the NetworkStream constructors (this involve using sockets);
  • By using TcpClient or UdpClient;
  • By using WebRequest or WebResponse.

Using the constructors
In order to create a NetworkStream using it's constructor, you will need a previously created Socket object. But you cannot use any type of socket. The socket must have been created with the SocketType.Stream value.

The available constructors are:
Failed to execute the [code] macro

The following sample shows you how to create an appropriate socket and the associated NetworkStream in the server case:

Failed to execute the [code] macro

And here is the client version:

Failed to execute the [code] macro

Related articles