NLNET::CListenSock Class Reference

#include <listen_sock.h>

Inheritance diagram for NLNET::CListenSock:

NLNET::CTcpSock NLNET::CSock

Detailed Description

CListenSock: listening socket for servers. How to accept connections in a simple server:
  1. Create a CListenSock object
  2. Listen on the port you want the clients to connect
  3. In a loop, accept a connection and store the new socket

Author:
Olivier Cado

Nevrax France

Date:
2000-2001

Definition at line 47 of file listen_sock.h.

Receiving data

bool dataAvailable ()
 Checks if there is some data to receive, waiting (blocking) at most for the time out value.

CSock::TSockResult receive (uint8 *buffer, uint32 &len, bool throw_exception=true)

Public Types

enum  TSockResult { Ok, WouldBlock, ConnectionClosed, Error }

Public Member Functions

CTcpSockaccept ()
 Blocks until an incoming connection is requested, accepts it, and creates a new socket (you have to delete it after use).

uint64 bytesReceived () const
 Returns the number of bytes received since the latest connection.

uint64 bytesSent () const
 Returns the number of bytes sent since the latest connection.

 CListenSock ()
 Constructor.

sint32 getSendBufferSize ()
 Gets the send buffer size.

void setSendBufferSize (sint32 size)
 Sets the send buffer size.

void setTimeOutValue (long sec, long ms)
 Change the time out value used in getDataAvailable(), which is 0 by default.

Socket setup
void connectWithCustomWindowSize (const CInetAddress &addr, int windowsize)
uint32 getWindowSize ()
 Returns the TCP Window Size for the current socket.

void shutdownReceiving ()
 Active disconnection for download way only (partial shutdown).

void shutdownSending ()
 Active disconnection for upload way only (partial shutdown).

Socket setup
sint backlog () const
 Returns the pending connections queue.

void init (const CInetAddress &addr)
 Prepares to receive connections on a specified address/port (useful when the host has several addresses).

void init (uint16 port)
 Prepares to receive connections on a specified port (bind+listen).

void setBacklog (sint backlog)
 Sets the number of the pending connections queue, or -1 for the maximum possible value.

Socket setup
virtual void connect (const CInetAddress &addr)
void connectWithCustomWindowSize (const CInetAddress &addr, int windowsize)
virtual void disconnect ()
 Active disconnection (shutdown) (mutexed). connected() becomes false.

uint32 getWindowSize ()
 Returns the TCP Window Size for the current socket.

virtual void setNoDelay (bool value)
void shutdownReceiving ()
 Active disconnection for download way only (partial shutdown).

void shutdownSending ()
 Active disconnection for upload way only (partial shutdown).


Static Public Member Functions

std::string errorString (uint errorcode)
 Returns a string explaining the network error (see getLastError()).

uint getLastError ()
bool initialized ()
 Returns true if the network engine is initialized.

void initNetwork ()
 Initialize the network engine, if it is not already done.

void releaseNetwork ()
 Releases the network engine.


Protected Member Functions

void createSocket (int type, int protocol)
 Creates the socket and get a valid descriptor.

void setLocalAddress ()
 Sets the local address.


Protected Attributes

uint64 _BytesReceived
 Number of bytes received on this socket.

uint64 _BytesSent
 Number of bytes sent on this socket.

volatile bool _Connected
 True after calling connect().

CInetAddress _LocalAddr
 Address of local host (valid if connected).

bool _Logging
 If false, do not log any information.

bool _NonBlocking
 If true, the socket is in nonblocking mode.

CInetAddress _RemoteAddr
 Address of the remote host (valid if connected).

SOCKET _Sock
 Socket descriptor.

long _TimeoutMs
 Secondary time out value (ms) for select in dataAvailable().

long _TimeoutS
 Main time out value (sec) for select in dataAvailable().


Private Attributes

sint _BackLog
bool _Bound


Member Enumeration Documentation

enum NLNET::CSock::TSockResult [inherited]
 

Enumeration values:
Ok 
WouldBlock 
ConnectionClosed 
Error 

Definition at line 125 of file sock.h.


Constructor & Destructor Documentation

NLNET::CListenSock::CListenSock  ) 
 

Constructor.

Todo:
cado: tune backlog value, not too small, not to big (20-200) to prevent SYN attacks (see http://www.cyberport.com/~tangent/programming/winsock/advanced.html)

Definition at line 63 of file listen_sock.cpp.

References NLNET::CSock::createSocket(), and setBacklog().

00063                          : CTcpSock(), _Bound( false )
00064 {
00065         // Create socket
00066         createSocket( SOCK_STREAM, IPPROTO_TCP );
00067 
00069         setBacklog( -1 );
00070 }


Member Function Documentation

CTcpSock * NLNET::CListenSock::accept  ) 
 

Blocks until an incoming connection is requested, accepts it, and creates a new socket (you have to delete it after use).

Definition at line 129 of file listen_sock.cpp.

References addr, NLNET::CTcpSock::CTcpSock(), and nldebug.

Referenced by NLNET::CListenTask::run().

00130 {
00131         // Accept connection
00132         sockaddr_in saddr;
00133         socklen_t saddrlen = sizeof(saddr);
00134         SOCKET newsock = ::accept( _Sock, (sockaddr*)&saddr, &saddrlen );
00135         if ( newsock == INVALID_SOCKET )
00136         {
00137           /*nlinfo( "LNETL0: Error accepting a connection");
00138           // See accept() man on Linux
00139           newsock = ::accept( _Sock, (sockaddr*)&saddr, &saddrlen );
00140           if ( newsock == INVALID_SOCKET )*/
00141             {
00142                         throw ESocket( "Accept returned an invalid socket");
00143             }
00144         }
00145 
00146         // Construct and save a CTcpSock object
00147         CInetAddress addr;
00148         addr.setSockAddr( &saddr );
00149         nldebug( "LNETL0: Socket %d accepted an incoming connection from %s, opening socket %d", _Sock, addr.asString().c_str(), newsock );
00150         CTcpSock *connection = new CTcpSock( newsock, addr );
00151         return connection;
00152 }

sint NLNET::CListenSock::backlog  )  const [inline]
 

Returns the pending connections queue.

Definition at line 67 of file listen_sock.h.

References _BackLog, and sint.

00067 { return _BackLog; }

uint64 NLNET::CSock::bytesReceived  )  const [inline, inherited]
 

Returns the number of bytes received since the latest connection.

Definition at line 249 of file sock.h.

References uint64.

Referenced by NLNET::CBufClient::bytesDownloaded().

00249 { return _BytesReceived; }

uint64 NLNET::CSock::bytesSent  )  const [inline, inherited]
 

Returns the number of bytes sent since the latest connection.

Definition at line 252 of file sock.h.

References uint64.

Referenced by NLNET::CBufClient::bytesUploaded().

00252 { return _BytesSent; }

virtual void NLNET::CSock::close  )  [virtual, inherited]
 

Closes the socket (without shutdown) In general you don't need to call this method. But you can call it to:

  • close a listening socket (i.e. stop accepting connections), or
  • stop a select() in progress in another thread (in this case, just calling the destructor is not enough)

Reimplemented in NLNET::CDummyTcpSock.

Referenced by NLNET::CUdpSimSock::close(), NLNET::CListenTask::close(), NLNET::CTcpSock::connect(), and NLNET::sendEmail().

void NLNET::CTcpSock::connect const CInetAddress addr  )  [virtual, inherited]
 

Connection. You can reconnect a socket after being disconnected. This method does not return a boolean, otherwise a programmer could ignore the result and no exception would be thrown if connection fails :

Reimplemented from NLNET::CSock.

Reimplemented in NLNET::CDummyTcpSock.

Definition at line 80 of file tcp_sock.cpp.

References addr, NLNET::CSock::close(), and NLNET::CSock::createSocket().

Referenced by NLNET::CBufSock::connect(), and NLNET::sendEmail().

00081 {
00082         // Create a new socket
00083         if ( _Sock != INVALID_SOCKET )
00084         {
00085           if ( _Logging )
00086             {
00087 //              nldebug( "LNETL0: Closing socket %d before reconnecting", _Sock );
00088             }
00089           close();
00090         }       
00091         createSocket( SOCK_STREAM, IPPROTO_TCP );
00092 
00093         // Connection
00094         CSock::connect( addr );
00095 }

bool NLNET::CSock::connected  )  [inherited]
 

Returns if the socket is connected (mutexed).

Referenced by NLNET::CCallbackClient::connect(), NLNET::CBufSock::connect(), NLNET::CBufClient::connect(), NLNET::CUdpSimSock::connected(), NLNET::CLoginClient::connectToShard(), NLNET::CBufServer::disconnect(), NLNET::CBufClient::disconnect(), NLNET::CBufSock::pushBuffer(), NLNET::sendEmail(), NLNET::CBufClient::update(), and NLNET::CBufClient::~CBufClient().

void NLNET::CTcpSock::connectWithCustomWindowSize const CInetAddress addr,
int  windowsize
[inherited]
 

Sets a custom TCP Window size (SO_RCVBUF and SO_SNDBUF). You must close the socket is necessary, before calling this method.

See http://www.ncsa.uiuc.edu/People/vwelch/net_perf/tcp_windows.html

Definition at line 161 of file tcp_sock.cpp.

References addr, NLNET::CSock::createSocket(), and nlerror.

00162 {
00163         // Create socket
00164         if ( _Sock != INVALID_SOCKET )
00165         {
00166                 nlerror( "Cannot connect with custom window size when already connected" );
00167         }
00168         createSocket( SOCK_STREAM, IPPROTO_TCP );
00169 
00170         // Change window size
00171         if ( setsockopt( _Sock, SOL_SOCKET, SO_SNDBUF, (char*)&windowsize, sizeof(windowsize) ) != 0
00172           || setsockopt( _Sock, SOL_SOCKET, SO_RCVBUF, (char*)&windowsize, sizeof(windowsize) ) != 0 )
00173         {
00174                 throw ESocket( "setWindowSize failed" );
00175         }
00176         
00177         // Connection
00178         CSock::connect( addr );
00179 }

void NLNET::CSock::createSocket int  type,
int  protocol
[protected, inherited]
 

Creates the socket and get a valid descriptor.

Referenced by CListenSock(), NLNET::CTcpSock::connect(), NLNET::CTcpSock::connectWithCustomWindowSize(), and NLNET::CUdpSock::CUdpSock().

bool NLNET::CSock::dataAvailable  )  [inherited]
 

Checks if there is some data to receive, waiting (blocking) at most for the time out value.

Referenced by NLNET::CUdpSimSock::dataAvailable(), and NLNET::CClientReceiveTask::run().

SOCKET NLNET::CSock::descriptor  )  const [inline, inherited]
 

Returns the socket descriptor.

Definition at line 241 of file sock.h.

References NLNET::CSock::_Sock.

Referenced by NLNET::CBufSock::asString(), and NLNET::CListenTask::run().

00241 { return _Sock; }

void NLNET::CTcpSock::disconnect  )  [virtual, inherited]
 

Active disconnection (shutdown) (mutexed). connected() becomes false.

Reimplemented in NLNET::CDummyTcpSock.

Definition at line 101 of file tcp_sock.cpp.

References NLNET::CInetAddress::asString(), and nldebug.

Referenced by NLNET::CBufSock::disconnect(), NLNET::CBufServer::disconnect(), NLNET::CClientReceiveTask::run(), and NLNET::CBufClient::update().

00102 {
00103         nldebug( "LNETL0: Socket %d disconnecting from %s...", _Sock, _RemoteAddr.asString().c_str() );
00104 
00105         // This shutdown resets the connection immediatly (not a graceful closure)
00106 #ifdef NL_OS_WINDOWS
00107         ::shutdown( _Sock, SD_BOTH );
00108 #elif defined NL_OS_UNIX
00109         ::shutdown( _Sock, SHUT_RDWR );
00110 #endif
00111         /*CSynchronized<bool>::CAccessor sync( &_SyncConnected );
00112         sync.value() = false;*/
00113         _Connected = false;
00114 }

std::string NLNET::CSock::errorString uint  errorcode  )  [static, inherited]
 

Returns a string explaining the network error (see getLastError()).

uint NLNET::CSock::getLastError  )  [static, inherited]
 

Returns the code of the last error that has occured. Note: This code is platform-dependant. On Unix, it is errno; on Windows it is the Winsock error code. See also errorString()

sint32 NLNET::CSock::getSendBufferSize  )  [inherited]
 

Gets the send buffer size.

uint32 NLNET::CTcpSock::getWindowSize  )  [inherited]
 

Returns the TCP Window Size for the current socket.

Definition at line 185 of file tcp_sock.cpp.

References len, and uint32.

00186 {
00187         int windowsize = 0;
00188         socklen_t len = sizeof( windowsize );
00189 
00190         /* send buffer -- query for buffer size */
00191         if ( getsockopt( _Sock, SOL_SOCKET, SO_SNDBUF, (char*) &windowsize, &len ) == 0 )
00192         {
00193                 return windowsize;
00194         }
00195         else
00196         {
00197                 return 0;
00198         }
00199 }

void NLNET::CListenSock::init const CInetAddress addr  ) 
 

Prepares to receive connections on a specified address/port (useful when the host has several addresses).

Definition at line 93 of file listen_sock.cpp.

References _BackLog, _Bound, addr, nldebug, and value.

00094 {
00095         if ( ! addr.isValid() )
00096         {
00097                 nldebug( "LNETL0: Binding listen socket to any address, port %hu", addr.port() );
00098         }
00099 
00100 #ifndef NL_OS_WINDOWS
00101         // Set Reuse Address On (does not work on Win98 and is useless on Win2000)
00102         int value = true;
00103         if ( setsockopt( _Sock, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value) ) == SOCKET_ERROR )
00104         {
00105                 throw ESocket( "ReuseAddr failed" );
00106         }
00107 #endif
00108 
00109         // Bind socket to port  
00110         if ( ::bind( _Sock, (const sockaddr *)addr.sockAddr(), sizeof(sockaddr_in) ) != 0 )
00111         {
00112                 throw ESocket( "Unable to bind listen socket to port" );
00113         }
00114         _LocalAddr = addr;
00115         _Bound = true;
00116 
00117         // Listen
00118         if ( ::listen( _Sock, _BackLog ) != 0 ) // SOMAXCONN = maximum length of the queue of pending connections
00119         {
00120                 throw ESocket( "Unable to listen on specified port" );
00121         }
00122 //      nldebug( "LNETL0: Socket %d listening at %s", _Sock, _LocalAddr.asString().c_str() );
00123 }

void NLNET::CListenSock::init uint16  port  ) 
 

Prepares to receive connections on a specified port (bind+listen).

Definition at line 76 of file listen_sock.cpp.

References NLNET::CInetAddress::asString(), nldebug, NLNET::CInetAddress::setPort(), and uint16.

Referenced by NLNET::CListenTask::init().

00077 {
00078     // Use any address
00079         CInetAddress localaddr; // By default, INETADDR_ANY (useful for gateways that have several ip addresses)
00080         localaddr.setPort( port );
00081         init( localaddr );
00082 
00083         // Now set the address visible from outside
00084         _LocalAddr = CInetAddress::localHost();
00085         _LocalAddr.setPort( port );
00086         nldebug( "LNETL0: Socket %d listen socket is at %s", _Sock, _LocalAddr.asString().c_str() );
00087 }

bool NLNET::CSock::initialized  )  [inline, static, inherited]
 

Returns true if the network engine is initialized.

Definition at line 261 of file sock.h.

00261 { return CSock::_Initialized; }

void NLNET::CSock::initNetwork  )  [static, inherited]
 

Initialize the network engine, if it is not already done.

const CInetAddress& NLNET::CSock::localAddr  )  const [inline, inherited]
 

Returns a const reference on the local address.

Definition at line 235 of file sock.h.

References NLNET::CSock::_LocalAddr.

Referenced by NLNET::CLoginServer::init(), NLNET::CUdpSimSock::localAddr(), and NLNET::CListenTask::localAddr().

00235 {       return _LocalAddr; }

bool NLNET::CSock::nonBlockingMode  )  const [inline, inherited]
 

Returns the nonblocking mode.

Definition at line 166 of file sock.h.

References NLNET::CSock::_NonBlocking.

00166 { return _NonBlocking; }

CSock::TSockResult NLNET::CSock::receive uint8 buffer,
uint32 len,
bool  throw_exception = true
[inherited]
 

Receive a partial or an entire block of data, depending on nonblocking mode.

In blocking mode: the method waits until 'len' bytes have been received.

In nonblocking mode: the method reads the bytes that have already been received only, and resets 'len' to the number of bytes read. The actual length may be smaller than the demanded length. In no data is available, the return value is CSock::WouldBlock. If dataAvailable() returns true, you are sure that receive() will not return CSock::WouldBlock.

In case of graceful disconnection:

In case of failure (e.g. connection reset by peer) :

  • the return value is CSock::Error or an ESocket exception is thrown. You may want to close the connection manually.

Reimplemented in NLNET::CUdpSock.

Referenced by NLNET::CNonBlockingBufSock::receivePart(), and NLNET::sendEMailCommand().

void NLNET::CSock::releaseNetwork  )  [static, inherited]
 

Releases the network engine.

const CInetAddress& NLNET::CSock::remoteAddr  )  const [inline, inherited]
 

Returns the address of the remote host.

Definition at line 238 of file sock.h.

References NLNET::CSock::_RemoteAddr.

Referenced by NLNET::CBufServer::hostAddress(), NLNET::CNonBlockingBufSock::receivePart(), NLNET::CBufClient::remoteAddress(), and NLNET::sendEMailCommand().

00238 { return _RemoteAddr; }

CSock::TSockResult NLNET::CSock::send const uint8 buffer,
uint32 len,
bool  throw_exception = true
[inherited]
 

Sends a message.

In blocking mode: the method waits until 'len' bytes have been sent.

In nonblocking mode : the method resets len to the actual number of bytes sent. Even if less bytes than expected have been sent, it returns CSock::Ok. The caller is expected to test the actual len to check if the remaining data must be resent.

Returns:
CSock::Ok or CSock::Error (in case of failure). When throw_exception is true, the method throws an ESocket exception in case of failure.

Referenced by NLNET::CBufSock::flush(), NLNET::sendEMailCommand(), and NLNET::CUdpSimSock::sendUDPNow().

void NLNET::CListenSock::setBacklog sint  backlog  ) 
 

Sets the number of the pending connections queue, or -1 for the maximum possible value.

Definition at line 158 of file listen_sock.cpp.

References _BackLog, _Bound, and sint.

Referenced by CListenSock().

00159 {
00160         if ( backlog == -1 )
00161         {
00162                 _BackLog = SOMAXCONN; // SOMAXCONN = maximum length of the queue of pending connections
00163         }
00164         else
00165         {
00166                 _BackLog = backlog;
00167         }
00168         if ( _Bound )
00169         {
00170                 if ( ::listen( _Sock, _BackLog ) != 0 )
00171                 {
00172                         throw ESocket( "Unable to listen on specified port, while changing backlog" );
00173                 }
00174         }
00175 }

void NLNET::CSock::setLocalAddress  )  [protected, inherited]
 

Sets the local address.

Referenced by NLNET::CUdpSock::bind(), and NLNET::CUdpSock::sendTo().

void NLNET::CTcpSock::setNoDelay bool  value  )  [virtual, inherited]
 

Sets/unsets TCP_NODELAY (by default, it is off, i.e. the Nagle buffering algorithm is enabled). You must call this method *after* connect().

Reimplemented in NLNET::CDummyTcpSock.

Definition at line 146 of file tcp_sock.cpp.

References value.

Referenced by NLNET::CBufSock::connect(), and NLNET::CListenTask::run().

00147 {
00148         int b = value?1:0;
00149         if ( setsockopt( _Sock, IPPROTO_TCP, TCP_NODELAY, (char*)&b, sizeof(b) ) != 0 )
00150         {
00151                 throw ESocket( "setNoDelay failed" );
00152         }
00153 }

void NLNET::CSock::setNonBlockingMode bool  bm  )  [inherited]
 

Sets the socket in nonblocking mode. Call this method *after* connect(), otherwise you will get an "would block" error (10035 on Windows). In nonblocking mode, use received() and sent() instead of receive() and send()

Referenced by NLNET::CNonBlockingBufSock::setNonBlocking().

void NLNET::CSock::setSendBufferSize sint32  size  )  [inherited]
 

Sets the send buffer size.

void NLNET::CSock::setTimeOutValue long  sec,
long  ms
[inline, inherited]
 

Change the time out value used in getDataAvailable(), which is 0 by default.

Definition at line 143 of file sock.h.

References NLNET::CSock::_TimeoutMs, and NLNET::CSock::_TimeoutS.

Referenced by NLNET::CClientReceiveTask::run().

00144         {
00145                 _TimeoutS = sec;
00146                 _TimeoutMs = ms;
00147         }

void NLNET::CTcpSock::shutdownReceiving  )  [inherited]
 

Active disconnection for download way only (partial shutdown).

Definition at line 120 of file tcp_sock.cpp.

00121 {
00122 #ifdef NL_OS_WINDOWS
00123         ::shutdown( _Sock, SD_RECEIVE );
00124 #elif defined NL_OS_UNIX
00125         ::shutdown( _Sock, SHUT_RD );
00126 #endif
00127 }

void NLNET::CTcpSock::shutdownSending  )  [inherited]
 

Active disconnection for upload way only (partial shutdown).

Definition at line 133 of file tcp_sock.cpp.

00134 {
00135 #ifdef NL_OS_WINDOWS
00136         ::shutdown( _Sock, SD_SEND );
00137 #elif defined NL_OS_UNIX
00138         ::shutdown( _Sock, SHUT_WR );
00139 #endif
00140 }

uint32 NLNET::CSock::timeOutValue  )  const [inline, inherited]
 

Returns the time out value in millisecond.

Definition at line 244 of file sock.h.

References NLNET::CSock::_TimeoutMs, NLNET::CSock::_TimeoutS, and uint32.

00244 { return _TimeoutS*1000 + _TimeoutMs; }


Field Documentation

sint NLNET::CListenSock::_BackLog [private]
 

Definition at line 78 of file listen_sock.h.

Referenced by backlog(), init(), and setBacklog().

bool NLNET::CListenSock::_Bound [private]
 

Definition at line 76 of file listen_sock.h.

Referenced by init(), and setBacklog().

uint64 NLNET::CSock::_BytesReceived [protected, inherited]
 

Number of bytes received on this socket.

Definition at line 300 of file sock.h.

uint64 NLNET::CSock::_BytesSent [protected, inherited]
 

Number of bytes sent on this socket.

Definition at line 303 of file sock.h.

volatile bool NLNET::CSock::_Connected [protected, inherited]
 

True after calling connect().

Definition at line 297 of file sock.h.

CInetAddress NLNET::CSock::_LocalAddr [protected, inherited]
 

Address of local host (valid if connected).

Definition at line 284 of file sock.h.

Referenced by NLNET::CSock::localAddr().

bool NLNET::CSock::_Logging [protected, inherited]
 

If false, do not log any information.

Definition at line 290 of file sock.h.

bool NLNET::CSock::_NonBlocking [protected, inherited]
 

If true, the socket is in nonblocking mode.

Definition at line 293 of file sock.h.

Referenced by NLNET::CSock::nonBlockingMode().

CInetAddress NLNET::CSock::_RemoteAddr [protected, inherited]
 

Address of the remote host (valid if connected).

Definition at line 287 of file sock.h.

Referenced by NLNET::CSock::remoteAddr().

SOCKET NLNET::CSock::_Sock [protected, inherited]
 

Socket descriptor.

Definition at line 281 of file sock.h.

Referenced by NLNET::CSock::descriptor().

long NLNET::CSock::_TimeoutMs [protected, inherited]
 

Secondary time out value (ms) for select in dataAvailable().

Definition at line 309 of file sock.h.

Referenced by NLNET::CSock::setTimeOutValue(), and NLNET::CSock::timeOutValue().

long NLNET::CSock::_TimeoutS [protected, inherited]
 

Main time out value (sec) for select in dataAvailable().

Definition at line 306 of file sock.h.

Referenced by NLNET::CSock::setTimeOutValue(), and NLNET::CSock::timeOutValue().


The documentation for this class was generated from the following files:
Generated on Tue Mar 16 13:58:13 2004 for NeL by doxygen 1.3.6