My Project
Public Types | Public Member Functions | Friends | List of all members
NPL::CNPLConnection Class Reference

A incoming or outgoing connection. More...

#include <NPLConnection.h>

Inheritance diagram for NPL::CNPLConnection:

Public Types

enum  ProtocolType { NPL = 0, WEBSOCKET = 1, TCP_CUSTOM = 2 }
 
typedef concurrent_ptr_queue< NPLMsgOut_ptr, dummy_condition_variableRingBuffer_Type
 
typedef std::map< std::string, int > StringMap_Type
 

Public Member Functions

 CNPLConnection (boost::asio::io_service &io_service, CNPLConnectionManager &manager, CNPLDispatcher &msg_dispatcher)
 Construct a connection with the given io_service. More...
 
boost::asio::ip::tcp::socket & socket ()
 Get the socket associated with the connection.
 
void start ()
 Start the first asynchronous operation for the connection.
 
void stop (bool bRemoveConnection=true, int nReason=0)
 Stop all asynchronous operations associated with the connection. More...
 
void CloseAfterSend ()
 close/stop the connection when all data has been sent
 
void connect ()
 connect to the remote NPL runtime address. More...
 
CNPLConnectionManagerGetConnectionManager ()
 return the connection manager.
 
NPLReturnCode SendMessage (const NPLFileName &file_name, const char *code=NULL, int nLength=0, int priority=0)
 Send a message via this connection. More...
 
NPLReturnCode SendMessage (const NPLMessage &msg)
 Send a message via this connection. More...
 
NPLReturnCode SendMessage (const char *sCommandName, const char *sCommandData)
 Send a message via this connection. More...
 
NPLReturnCode SendMessage (NPLMsgOut_ptr &msg)
 send a raw NPL output message to the stream. More...
 
void SetNPLRuntimeAddress (NPLRuntimeAddress_ptr runtime_address)
 set the NPL runtime address that this connection connects to. More...
 
virtual void GetStatistics (int &totalIn, int &totalOut)
 Get statistics about this connection. More...
 
NPLConnectionState GetState () const
 Returns the current connection state. More...
 
const string & GetNID () const
 Get the NPL runtime address ID if any. More...
 
string GetIP ()
 Get the TCP IP address if any. More...
 
string GetPort ()
 Get the TCP IP port if any. More...
 
bool SetNID (const char *sNID)
 set nid of this connection. More...
 
void SetAuthenticated (bool bAuthenticated)
 set whether this connection is authenticated. More...
 
bool IsAuthenticated () const
 whether this connection is authenticated. More...
 
bool IsConnected () const
 whether the connection is established or not. More...
 
void SetUseCompression (bool bUseCompression)
 set whether to use compression for this connection. More...
 
bool IsUseCompression ()
 get whether to use compression for this connection. More...
 
void SetCompressionLevel (int nLevel)
 default to 0, which means no compression. More...
 
int GetCompressionLevel ()
 
void SetCompressionThreshold (int nThreshold)
 when the message size is bigger than this number of bytes, we will use m_nCompressionLevel for compression. More...
 
int GetCompressionThreshold ()
 
void SetTCPKeepAlive (bool bEnable)
 set the TCP protocol level keep alive. More...
 
void SetKeepAlive (bool bEnable)
 enable application level keep alive. More...
 
bool IsKeepAliveEnabled ()
 
void EnableIdleTimeout (bool bEnable)
 Enable idle timeout. More...
 
bool IsIdleTimeoutEnabled ()
 
void SetIdleTimeoutPeriod (int nMilliseconds)
 how many milliseconds of inactivity to assume this connection should be timed out. More...
 
int GetIdleTimeoutPeriod ()
 
unsigned int GetLastActiveTime ()
 get the last time in milliseconds GetTickCount(), that a send/receive/connect message is transmitted via this connection. More...
 
void TickSend ()
 update the last send time. More...
 
void TickReceive ()
 update the last receive or connect time. More...
 
int CheckIdleTimeout (unsigned int nCurTime)
 if any of the connection should be timed out. More...
 
bool HasUnsentData ()
 whether there is unsent data. More...
 
int GetLogLevel ()
 get global log level. More...
 
void SetProtocol (ProtocolType protocolType=ProtocolType::NPL)
 set transmission protocol, default value is 0. More...
 
virtual bool handleReceivedData (int bytes_transferred)
 This function is called whenever some data is received from the underlying transport. More...
 
virtual void handleConnect ()
 This function is called when e.g. More...
 
virtual void handleDisconnect (int reason)
 This connection is called when e.g. More...
 
virtual bool handleMessageIn ()
 handle m_input_msg. More...
 

Friends

class CNPLDispatcher
 

Detailed Description

A incoming or outgoing connection.

It does the following things

Please note that the handle_XXX functions are asynchronous callbacks from the dispatcher thread.

Constructor & Destructor Documentation

§ CNPLConnection()

NPL::CNPLConnection::CNPLConnection ( boost::asio::io_service &  io_service,
CNPLConnectionManager manager,
CNPLDispatcher msg_dispatcher 
)
explicit

Construct a connection with the given io_service.

whether to enable tcp level keep alive.

Keep alive is a system socket feature

Member Function Documentation

§ CheckIdleTimeout()

int NPL::CNPLConnection::CheckIdleTimeout ( unsigned int  nCurTime)

if any of the connection should be timed out.

If so, send keep alive message or the caller should close it. This function is called by a global service timer that periodically does the checking for all active connections.

Returns
1 if not timed out. 0 if timed out,the caller should close the connection. -1 if timed out and keep alive is sent.

§ connect()

void NPL::CNPLConnection::connect ( )

connect to the remote NPL runtime address.

this function returns immediately. It will resolve host and then calls start().

§ EnableIdleTimeout()

void NPL::CNPLConnection::EnableIdleTimeout ( bool  bEnable)

Enable idle timeout.

This is the application level timeout setting. We will create a global timer which examines all send/receive time of all open connections, if a connection is inactive (idle for GetIdleTimeoutPeriod()) we will

  • if IsKeepAliveEnabled() is false, actively close the connection. This is the method used by HTTP, which is the only solution to detect broken connection without sending additional keep alive message.
  • if IsKeepAliveEnabled() is true, send an empty message to the other end (keep alive messages) to more accurately detect dead connections (see SetKeepAlive).

§ GetIP()

string NPL::CNPLConnection::GetIP ( )

Get the TCP IP address if any.

[thread safe]

§ GetLastActiveTime()

unsigned int NPL::CNPLConnection::GetLastActiveTime ( )

get the last time in milliseconds GetTickCount(), that a send/receive/connect message is transmitted via this connection.

[thread safe only in dispatcher thread]

§ GetLogLevel()

int NPL::CNPLConnection::GetLogLevel ( )

get global log level.

§ GetNID()

const string & NPL::CNPLConnection::GetNID ( ) const

Get the NPL runtime address ID if any.

[thread safe]

§ GetPort()

string NPL::CNPLConnection::GetPort ( )

Get the TCP IP port if any.

[thread safe]

§ GetState()

NPLConnectionState NPL::CNPLConnection::GetState ( ) const
inline

Returns the current connection state.

Function is not thread-safe

Returns
The state of the connection.

§ GetStatistics()

void NPL::CNPLConnection::GetStatistics ( int &  totalIn,
int &  totalOut 
)
virtual

Get statistics about this connection.

Function is not thread-safe, it is for debugging anyway.

§ handleConnect()

void NPL::CNPLConnection::handleConnect ( )
virtual

This function is called when e.g.

the raw TCP connection was established.

§ handleDisconnect()

void NPL::CNPLConnection::handleDisconnect ( int  reason)
virtual

This connection is called when e.g.

the raw TCP connection was closed.

Parameters
reasonThe reason for the disconnect.

§ handleMessageIn()

bool NPL::CNPLConnection::handleMessageIn ( )
virtual

handle m_input_msg.

After a complete message is read by the parser object, one should call this function. Once the message is handled, m_input_msg will be reset, so that more messages can be handled later on.

§ handleReceivedData()

bool NPL::CNPLConnection::handleReceivedData ( int  bytes_transferred)
virtual

This function is called whenever some data is received from the underlying transport.

the data is always in (m_buffer.data(), m_buffer.data()+bytes_transferred)

Parameters
bytes_transferredThe number of bytes received.
Returns
true if succeed, and one should continue reading from the socket. and false if connection should be closed.

§ HasUnsentData()

bool NPL::CNPLConnection::HasUnsentData ( )

whether there is unsent data.

§ IsAuthenticated()

bool NPL::CNPLConnection::IsAuthenticated ( ) const

whether this connection is authenticated.

Usually it is a the job of NPL runtime state to reject or authenticate a connection. The NPL server just accepts any incoming connections and assign a temporary nid. it is the job of the NPL runtime state to assign an authenticated new nid to this connection. See

§ IsConnected()

bool NPL::CNPLConnection::IsConnected ( void  ) const

whether the connection is established or not.

§ IsUseCompression()

bool NPL::CNPLConnection::IsUseCompression ( )

get whether to use compression for this connection.

§ SendMessage() [1/4]

NPL::NPLReturnCode NPL::CNPLConnection::SendMessage ( const NPLFileName file_name,
const char *  code = NULL,
int  nLength = 0,
int  priority = 0 
)

Send a message via this connection.

Parameters
file_namethe full qualified remote file name. Only relative path and runtime state name is used, other fields are ignored.
codeit is a chunk of pure data table init code that would be transmitted to the destination file.
nLengththe code length. if this is 0, length is determined from code by finding '\0',
priorityif 0 it is normal priority. if 1 it will be inserted to the front of the message queue.

§ SendMessage() [2/4]

NPL::NPLReturnCode NPL::CNPLConnection::SendMessage ( const NPLMessage msg)

Send a message via this connection.

this is usually called for sending a special message.

§ SendMessage() [3/4]

NPL::NPLReturnCode NPL::CNPLConnection::SendMessage ( const char *  sCommandName,
const char *  sCommandData 
)

Send a message via this connection.

this is usually called for sending a simple command message.

§ SendMessage() [4/4]

NPL::NPLReturnCode NPL::CNPLConnection::SendMessage ( NPLMsgOut_ptr &  msg)

send a raw NPL output message to the stream.

Message will fail if connection is not established, or queue is full. otherwise it will be added to the m_queueOutput

Parameters
msgthe msg should be created just before it.

§ SetAuthenticated()

void NPL::CNPLConnection::SetAuthenticated ( bool  bAuthenticated)

set whether this connection is authenticated.

§ SetCompressionLevel()

void NPL::CNPLConnection::SetCompressionLevel ( int  nLevel)

default to 0, which means no compression.

Compression level, which is an integer in the range of -1 to 9. Lower compression levels result in faster execution, but less compression. Higher levels result in greater compression, but slower execution. The zlib constant Z_DEFAULT_COMPRESSION, equal to -1, provides a good compromise between compression and speed and is equivalent to level 6. Level 0 actually does no compression at all, and in fact expands the data slightly to produce the zlib format (it is not a byte-for-byte copy of the input).

§ SetCompressionThreshold()

void NPL::CNPLConnection::SetCompressionThreshold ( int  nThreshold)

when the message size is bigger than this number of bytes, we will use m_nCompressionLevel for compression.

For message smaller than the threshold, we will not compress even m_nCompressionLevel is not 0.

§ SetIdleTimeoutPeriod()

void NPL::CNPLConnection::SetIdleTimeoutPeriod ( int  nMilliseconds)

how many milliseconds of inactivity to assume this connection should be timed out.

if 0 it is never timed out.

§ SetKeepAlive()

void NPL::CNPLConnection::SetKeepAlive ( bool  bEnable)

enable application level keep alive.

we will use a global idle timer to detect if a connection has been inactive for GetIdleTimeoutPeriod(), if so, we may send the keep alive message.

Parameters
bEnableenable keep alive will automatically enable EnableIdleTimeout()

§ SetNID()

bool NPL::CNPLConnection::SetNID ( const char *  sNID)

set nid of this connection.

If one renames a connection, such as changing from a temporary nid to authenticated nid. it will automatically update the nid to connection mapping in the dispatcher.

§ SetNPLRuntimeAddress()

void NPL::CNPLConnection::SetNPLRuntimeAddress ( NPLRuntimeAddress_ptr  runtime_address)

set the NPL runtime address that this connection connects to.

§ SetProtocol()

void NPL::CNPLConnection::SetProtocol ( ProtocolType  protocolType = ProtocolType::NPL)

set transmission protocol, default value is 0.

§ SetTCPKeepAlive()

void NPL::CNPLConnection::SetTCPKeepAlive ( bool  bEnable)

set the TCP protocol level keep alive.

default value depends on whether it is listening sockets or not. see CNPLNetServer::SetTCPKeepAlive

Note
: it is advised to use application level timeout. see SetKeepAlive().

§ SetUseCompression()

void NPL::CNPLConnection::SetUseCompression ( bool  bUseCompression)

set whether to use compression for this connection.

this is a candy function for SetCompressionLevel().

§ stop()

void NPL::CNPLConnection::stop ( bool  bRemoveConnection = true,
int  nReason = 0 
)

Stop all asynchronous operations associated with the connection.

Parameters
bRemoveConnectionif true(default), connection will be immediately removed from CNPLConnectionManager if false, one need to manually remove it from the CNPLConnectionManager
nReason0 is normal disconnect(it will abort pending read/write). 1 is another user with same nid is authenticated. The server should send a message to tell the client about this. -1 means close the connection when all pending data has been sent.

§ TickReceive()

void NPL::CNPLConnection::TickReceive ( )

update the last receive or connect time.

Internally, it just set the m_nLastActiveTime to GetTickCount(). [thread safe only in dispatcher thread]

§ TickSend()

void NPL::CNPLConnection::TickSend ( )

update the last send time.

Internally, it just set the m_nLastActiveTime to GetTickCount(). [thread safe only in dispatcher thread]


The documentation for this class was generated from the following files: