NLNET::CUdpSock Class Reference

#include <udp_sock.h>

Inheritance diagram for NLNET::CUdpSock:

NLNET::CSock

Detailed Description

CUdpSock: Unreliable datagram socket via UDP. See base class CSock.
Author:
Olivier Cado

Nevrax France

Date:
2000-2001

Definition at line 42 of file udp_sock.h.

Public Types

enum  TSockResult { Ok, WouldBlock, ConnectionClosed, Error }

Public Member Functions

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.

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.

Properties
bool connected ()
 Returns if the socket is connected (mutexed).

SOCKET descriptor () const
 Returns the socket descriptor.

const CInetAddresslocalAddr () const
 Returns a const reference on the local address.

const CInetAddressremoteAddr () const
 Returns the address of the remote host.

uint32 timeOutValue () const
 Returns the time out value in millisecond.

Socket setup
bool nonBlockingMode () const
 Returns the nonblocking mode.

void setNonBlockingMode (bool bm)
Sending data
CSock::TSockResult send (const uint8 *buffer, uint32 &len, bool throw_exception=true)
Socket setup
virtual void close ()
bool nonBlockingMode () const
 Returns the nonblocking mode.

void setNonBlockingMode (bool bm)
Properties
bool connected ()
 Returns if the socket is connected (mutexed).

SOCKET descriptor () const
 Returns the socket descriptor.

const CInetAddresslocalAddr () const
 Returns a const reference on the local address.

const CInetAddressremoteAddr () const
 Returns the address of the remote host.

uint32 timeOutValue () const
 Returns the time out value in millisecond.

Sending data
CSock::TSockResult send (const uint8 *buffer, uint32 &len, bool throw_exception=true)
Properties
bool connected ()
 Returns if the socket is connected (mutexed).

SOCKET descriptor () const
 Returns the socket descriptor.

const CInetAddresslocalAddr () const
 Returns a const reference on the local address.

const CInetAddressremoteAddr () const
 Returns the address of the remote host.

uint32 timeOutValue () const
 Returns the time out value in millisecond.

Sending data
CSock::TSockResult send (const uint8 *buffer, uint32 &len, bool throw_exception=true)
Socket setup
virtual void close ()
bool nonBlockingMode () const
 Returns the nonblocking mode.

void setNonBlockingMode (bool bm)
Properties
bool connected ()
 Returns if the socket is connected (mutexed).

SOCKET descriptor () const
 Returns the socket descriptor.

const CInetAddresslocalAddr () const
 Returns a const reference on the local address.

const CInetAddressremoteAddr () const
 Returns the address of the remote host.

uint32 timeOutValue () const
 Returns the time out value in millisecond.

Sending data
CSock::TSockResult send (const uint8 *buffer, uint32 &len, bool throw_exception=true)
Socket setup
void bind (const CInetAddress &addr)
 Same as bind(uint16) but binds on a specified address/port (useful when the host has several addresses).

void bind (uint16 port)
 CUdpSock (bool logging=true)
Socket setup
virtual void close ()
virtual void connect (const CInetAddress &addr)
bool nonBlockingMode () const
 Returns the nonblocking mode.

void setNonBlockingMode (bool bm)
Properties
bool connected ()
 Returns if the socket is connected (mutexed).

SOCKET descriptor () const
 Returns the socket descriptor.

const CInetAddresslocalAddr () const
 Returns a const reference on the local address.

const CInetAddressremoteAddr () const
 Returns the address of the remote host.

uint32 timeOutValue () const
 Returns the time out value in millisecond.

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

Receiving data
bool receive (uint8 *buffer, uint32 &len, bool throw_exception=true)
bool receivedFrom (uint8 *buffer, uint &len, CInetAddress &addr, bool throw_exception=true)
Sending data
CSock::TSockResult send (const uint8 *buffer, uint32 &len, bool throw_exception=true)
Sending data
void sendTo (const uint8 *buffer, uint len, const CInetAddress &addr)
 Sends data to the specified host (unreliable sockets only).


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

bool _Bound
 True after calling bind() or sendTo().


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::CUdpSock::CUdpSock bool  logging = true  ) 
 

Constructor.

Parameters:
logging Disable logging if the server socket object is used by the logging system, to avoid infinite recursion

Definition at line 62 of file udp_sock.cpp.

References NLNET::CSock::createSocket().

00062                                  :
00063         CSock( logging ),
00064         _Bound( false )
00065 {
00066         // Socket creation
00067         createSocket( SOCK_DGRAM, IPPROTO_UDP );
00068 }


Member Function Documentation

void NLNET::CUdpSock::bind const CInetAddress addr  ) 
 

Same as bind(uint16) but binds on a specified address/port (useful when the host has several addresses).

Definition at line 86 of file udp_sock.cpp.

References addr, NLNET::CInetAddress::asString(), nldebug, NLNET::CInetAddress::sockAddr(), and value.

00087 {
00088 #ifndef NL_OS_WINDOWS
00089         // Set Reuse Address On (does not work on Win98 and is useless on Win2000)
00090         int value = true;
00091         if ( setsockopt( _Sock, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value) ) == SOCKET_ERROR )
00092         {
00093                 throw ESocket( "ReuseAddr failed" );
00094         }
00095 #endif
00096 
00097         _LocalAddr = addr;
00098 
00099         // Bind the socket
00100         if ( ::bind( _Sock, (sockaddr*)(_LocalAddr.sockAddr()), sizeof(sockaddr) ) == SOCKET_ERROR )
00101         {
00102                 throw ESocket( "Bind failed" );
00103         }
00104         _Bound = true;
00105         if ( _Logging )
00106         {
00107                 nldebug( "LNETL0: Socket %d bound at %s", _Sock, _LocalAddr.asString().c_str() );
00108         }
00109 }

void NLNET::CUdpSock::bind uint16  port  ) 
 

Binds the socket to the specified port. Call bind() for an unreliable socket if the host acts as a server and expects to receive messages. If the host acts as a client, call directly sendTo(), in this case you need not bind the socket.

Definition at line 74 of file udp_sock.cpp.

References addr, NLNET::CSock::setLocalAddress(), and uint16.

00075 {
00076         CInetAddress addr; // any IP address
00077         addr.setPort( port );
00078         bind( addr );
00079         setLocalAddress(); // will not set the address if the host is multihomed, use bind(CInetAddress) instead
00080 }

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().

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

Connection. This method does not return a boolean, otherwise a programmer could ignore the result and no exception would be thrown if connection fails :

Reimplemented in NLNET::CDummyTcpSock, and NLNET::CTcpSock.

Referenced by NLNET::CUdpSimSock::connect(), and NLNET::CLoginClient::connectToShard().

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::CSock::createSocket int  type,
int  protocol
[protected, inherited]
 

Creates the socket and get a valid descriptor.

Referenced by NLNET::CListenSock::CListenSock(), NLNET::CTcpSock::connect(), NLNET::CTcpSock::connectWithCustomWindowSize(), and 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; }

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.

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

bool NLNET::CUdpSock::receive uint8 buffer,
uint32 len,
bool  throw_exception = true
 

Receives data from the peer. (blocking function) The socket must be pseudo-connected.

Reimplemented from NLNET::CSock.

Definition at line 156 of file udp_sock.cpp.

References NLNET::CInetAddress::asString(), buffer, len, nlassert, nldebug, uint32, and uint8.

Referenced by NLNET::CUdpSimSock::receive().

00157 {
00158         nlassert( _Connected && (buffer!=NULL) );
00159 
00160         // Receive incoming message
00161         len = ::recv( _Sock, (char*)buffer, len , 0 );
00162 
00163         // Check for errors (after setting the address)
00164         if ( ((int)len) == SOCKET_ERROR )
00165         {
00166                 if ( throw_exception )
00167                         throw ESocket( "Cannot receive data" );
00168                 return false;
00169         }
00170 
00171         _BytesReceived += len;
00172         if ( _Logging )
00173         {
00174                 nldebug( "LNETL0: Socket %d received %d bytes from peer %s", _Sock, len, _RemoteAddr.asString().c_str() );
00175         }
00176         return true;
00177 }

bool NLNET::CUdpSock::receivedFrom uint8 buffer,
uint len,
CInetAddress addr,
bool  throw_exception = true
 

Receives data and say who the sender is. (blocking function) The socket must have been bound before, by calling either bind() or sendTo().

Parameters:
buffer [in] Address of buffer
len [in/out] Requested length of buffer, and actual number of bytes received
addr [out] Address of sender

Definition at line 183 of file udp_sock.cpp.

References addr, buffer, len, nldebug, uint, and uint8.

Referenced by NLNET::CUdpSimSock::dataAvailable().

00184 {
00185         // Receive incoming message
00186         sockaddr_in saddr;
00187         socklen_t saddrlen = sizeof(saddr);
00188 
00189         len = ::recvfrom( _Sock, (char*)buffer, len , 0, (sockaddr*)&saddr, &saddrlen );
00190 
00191         // If an error occurs, the saddr is not valid
00192         // When the remote socket is closed, get sender's address to know who is quitting
00193         addr.setSockAddr( &saddr );
00194 
00195         // Check for errors (after setting the address)
00196         if ( ((int)len) == SOCKET_ERROR )
00197         {
00198                 if ( throw_exception )
00199                         throw ESocket( "Cannot receive data" );
00200                 return false;
00201         }
00202 
00203         _BytesReceived += len;
00204         if ( _Logging )
00205         {
00206                 nldebug( "LNETL0: Socket %d received %d bytes from %s", _Sock, len, addr.asString().c_str() );
00207         }
00208         return true;
00209 }

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::CUdpSock::sendTo const uint8 buffer,
uint  len,
const CInetAddress addr
 

Sends data to the specified host (unreliable sockets only).

Definition at line 115 of file udp_sock.cpp.

References addr, buffer, len, nldebug, nlinfo, NLNET::CSock::setLocalAddress(), sint32, size, uint, and uint8.

Referenced by NLNET::CUdpSimSock::sendUDPNow().

00116 {
00117         
00118         //  Send
00119         if ( ::sendto( _Sock, (const char*)buffer, len, 0, (sockaddr*)(addr.sockAddr()), sizeof(sockaddr) ) != (sint32)len )
00120         {
00121                 throw ESocket( "Unable to send datagram" );
00122         }
00123         _BytesSent += len;
00124 
00125         if ( _Logging )
00126         {
00127                 nldebug( "LNETL0: Socket %d sent %d bytes to %s", _Sock, len, addr.asString().c_str() );
00128         }
00129 
00130         // If socket is unbound, retrieve local address
00131         if ( ! _Bound )
00132         {
00133                 setLocalAddress();
00134                 _Bound = true;
00135         }
00136 
00137 #ifdef NL_OS_WINDOWS
00138         // temporary by ace to know size of SO_MAX_MSG_SIZE
00139         static bool first = true;
00140         if (first)
00141         {
00142                 uint MMS, SB;
00143                 int  size = sizeof (MMS);
00144                 getsockopt (_Sock, SOL_SOCKET, SO_SNDBUF, (char *)&SB, &size);
00145                 getsockopt (_Sock, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&MMS, &size);
00146                 nlinfo ("LNETL0: The udp SO_MAX_MSG_SIZE=%u, SO_SNDBUF=%u", MMS, SB);
00147                 first = false;
00148         }
00149 #endif
00150 }

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

Sets the local address.

Referenced by bind(), and sendTo().

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         }

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

bool NLNET::CUdpSock::_Bound [private]
 

True after calling bind() or sendTo().

Definition at line 95 of file udp_sock.h.

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 14:06:02 2004 for NeL by doxygen 1.3.6