A Stream Socket API for C++

Use of standard socket libraries can be a little intimidating knowing what to call, when to call it, how to set the right parameters and which ones to leave alone. This interface for c++ provides a simpler interface to use. If you think about it, even the reading from the stream works like standard character streams and will block when data is not available.

This library and example is provided by Rob Tougher in an article from the Linux Gazette. His permission has been granted to use this library for class purposes. If you use it otherwise, it is up to you to gain permission for use in your application.


Socket.cpp provides the wrapper API for the basic calls used in standard c examples.
The public procedures available are:
  virtual ~Socket();

  // Server initialization
  bool create();
  bool bind ( const int port );
  bool listen() const;
  bool accept ( Socket& ) const;

  // Client initialization
  bool connect ( const std::string host, const int port );

  // Data Transimission
  bool send ( const std::string ) const;
  int recv ( std::string& ) const;

  void set_non_blocking ( const bool );

  bool is_valid() const { return m_sock != -1; }

The Socket class is defined to be used to create the ServerSocket class. The ServerSocket class basically adds exception handling and provides a stream interface.

An example of the use of the ServerSocket is shown below. The example simply echos whatever is sent to it.

int main ( int argc, int argv[] )
  std::cout << "running....\n";
          // Create the listening socket
      ServerSocket server ( 30000 );

      while ( true )
        {    //create the conversational socket
          ServerSocket new_sock;
             // wait for a client connection
          server.accept ( new_sock );

              while ( true )
                {  // read the string and write it back
                  std::string data;
                  new_sock >> data;
                  new_sock << data;
          catch ( SocketException& ) {}

  catch ( SocketException& e )
      std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";

  return 0;

Feel free to adapt this to your assignments if you are more comfortable with c++.
A Makefile is also provided for your convenience along with client files in ~dgame/www/sockets/socketsC++.