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:
public NetworkStream(Socket socket);
public NetworkStream(Socket socket, bool ownsSocket);
public NetworkStream(Socket socket, FileAccess access);
public NetworkStream(Socket socket, FileAccess access, bool ownsSocket);

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

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketServer
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Socket sock = null;
IPAddress ipa = IPAddress.Loopback;
IPEndPoint ipe = new IPEndPoint(ipa, 6500);

sock = new Socket(ipa.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Binding...");
sock.Bind(ipe);
Console.WriteLine("Listening for client...");
sock.Listen(2);
Console.WriteLine("Accepting client...");
Socket clientSocket = sock.Accept();
Console.WriteLine("Client Connected");
NetworkStream ns = new NetworkStream(clientSocket);
byte[] textBuffer = Encoding.UTF8.GetBytes("Hello World!");
byte length = Convert.ToByte(textBuffer.Length);
Console.WriteLine("Sending data");
ns.Write(new byte[] {length}, 0, 1);
ns.Write(textBuffer,0, textBuffer.Length);
ns.Flush();
Console.WriteLine("Closing connection");
ns.Close();

Console.WriteLine("Terminating server");
}
}
}

And here is the client version:

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace SocketClient
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
IPAddress ipServer = IPAddress.Loopback;
IPEndPoint ipe = new IPEndPoint(ipServer, 6500);
Socket s = new Socket(ipServer.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Connect(ipe);

NetworkStream ns = new NetworkStream(s);
int txtLength = ns.ReadByte();
byte[] text = new byte[txtLength];
ns.Read(text,0, txtLength);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(text));
ns.Close();
}
}
}

Related articles