Thursday, January 4, 2007

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.


--------------------------------------------------------------------------------

Server
Socket.cpp provides the wrapper API for the basic calls used in standard c examples.
The public procedures available are:
--------------------------------------------------------------------------------

public:
Socket();
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";
try
{
// 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 );

try
{
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;
}
}

No comments:

Thats mee ...

Thats mee ...

About Me

Delhi, Delhi, India
I am an Electrical Engineering student of Indian Institute of Technology, Delhi. I am currently in 5th year of my Dual Degree course. By the end of this course I will proudly be called Masters in Information and Communication Technology. I have hard core programming interest and good at Networking Fundamentals. Enjoy surfing around Linux journals.