Extending the iostream (work in progress !!)

The C++ iostream class supports I/O on files and a couple of standard streams like cout, cin and cerr with a load of functionality such as formatting, handling of several input and output types and flexible control. The iostream can be extended fairly easily to support other types of streams. This page explains how to do this by guiding you through an example that implements a client-server system using sockets as streams.

The iosockstream class is derived from iostream, thus inherits iostream's functionality. iostream uses a stream buffer to interface with the actual input/output, in our case the socket.

Two important member functions in streambuf are setg() and setp(). setg() initialises a get area (gbuf) for reading from the socket using >>, setp() does the same for a put area (pbuf) that is used to write to the socket using <<.

The diagram below shows the use of the get- and put-buffers.

Reading from sockstream (mystream >> c)

Bytes read from the socket are stored into gbuf. After reading a number of bytes, the buffer pointer is updated using gptr().

Writing to sockstream (mystream << c)

Bytes to write to the socket are stored into pbuf and of bytes, the buffer pointer is updated using gptr();

C++ Source:
sockbuf.h
sockstream.h
sockstream.cpp
sockstream_main.cpp