int status = ::send ( m_sock, s.c_str(), s.size(), MSG_NOSIGNAL );
if ( status == -1 )
{
return false;
}
else
{
return true;
}
}
int Socket::recv ( string& s ) const
{
char buf [ MAXRECV + 1 ];
s = "";
memset ( buf, 0, MAXRECV + 1 );
int status = ::recv ( m_sock, buf, MAXRECV, 0 );
if ( status == -1 )
{
cout <
return 0;
}
else if ( status == 0 )
{
return 0;
}
else
{
s = buf;
return status;
}
}
bool Socket::connect ( const string host, const int port )
{
if ( ! is_valid() ) return false;
m_addr.sin_family = AF_INET;
m_addr.sin_port = htons ( port );
int status = inet_pton ( AF_INET, host.c_str(), &m_addr.sin_addr );
if ( errno == EAFNOSUPPORT ) return false;
status = ::connect ( m_sock, ( sockaddr * ) &m_addr, sizeof ( m_addr ) );
if ( status == 0 )
return true;
else
return false;
}
void Socket::set_non_blocking ( const bool b )
{
int opts;
opts = fcntl ( m_sock,
F_GETFL );
if ( opts
{
return;
}
if ( b )
opts = ( opts | O_NONBLOCK );
else
opts = ( opts & ~O_NONBLOCK );
fcntl ( m_sock,
F_SETFL,opts );
}
ServerSocket.h
// Definition of the ServerSocket class
#ifndef ServerSocket_class
#define ServerSocket_class
#include "Socket.h"
class ServerSocket : private Socket
{
public:
ServerSocket ( int port );
ServerSocket (){};
virtual ~ServerSocket();
const ServerSocket& operator <
const ServerSocket& operator >> ( std::string& ) const;
void accept ( ServerSocket& );
};
#endif
ServerSocket.cpp
// Implementation of the ServerSocket class
#include "ServerSocket.h"
#include "SocketException.h"
ServerSocket::ServerSocket ( int port )
{
if ( ! Socket::create() )
{
throw SocketException ( "Could not create server socket." );
}
if ( ! Socket::bind ( port ) )
{
throw SocketException ( "Could not bind to port." );
}
if ( ! Socket::listen() )
{
throw SocketException ( "Could not listen to socket." );
}
}
ServerSocket::~ServerSocket()
{
}
const ServerSocket& ServerSocket::operator <
{
if ( ! Socket::send ( s ) )
{
throw SocketException ( "Could not write to socket." );
}
return *this;
}
const ServerSocket& ServerSocket::operator >> ( std::string& s ) const