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.
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; }
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;
}
}