Monday 13 August 2012

Art of C# Sockets II: "Lineage" of NetworkStream

What is a NetworkStream? Specifically what makes it unique from its abstract base class Stream.

A network stream is like a stream of water, only instead of H20 going from the top of the mountain to the valley below, we instead have "molecules" of data (which we call bytes)  travelling continuously from a source to a destination. If the source and desination are at different parts of a computer network, the connecting byte stream can be loosely termed a "NetworkStream".

Ok, so we know vaguely know what a Network Stream, as they call it, is all about. Where does the NetworkStream class come from? What's its lineage, so to speak, in terms of the object model/class hierarchy.

Stream is the abstract base class of all Streams (the top of the Himalayas, if you will). Stream is the only class that NetworkStream directly subclasses from. Indirectly, NetworkStream also inherits from MarshalByRefObject and System.Object but these are rather peripheral facts (we'll look at the esoteric implications much later).

NetworkStream is a specialization of a Stream that supports reading, writing and seeking for Streams over the Network and lives in the System.Net.Sockets namespace. The class is very useful when writing TCP clients and servers.

NetworkStream extends System.IO.Stream. Has methods to read and write byte arrays. Streams also provide seeking capabilities - ability to query and modify the current position within a stream.

What is the practical usage of NetworkStream?

To send messages from TCP client to server.

No comments: