My Project
NPLConnection.h
1 #pragma once
2 #include "NPLMessage.h"
3 #include "NPLCommon.h"
4 #include "NPLMsgIn.h"
5 #include "NPLMsgOut.h"
6 #include "NPLMsgIn_parser.h"
7 #include "NPLMessageQueue.h"
8 #include "WebSocket/WebSocketReader.h"
9 #include "WebSocket/WebSocketWriter.h"
10 
11 #include <boost/asio.hpp>
12 #include <boost/array.hpp>
13 #include <boost/noncopyable.hpp>
14 #include <boost/shared_ptr.hpp>
15 #include <boost/enable_shared_from_this.hpp>
16 
17 namespace NPL
18 {
19  class CNPLDispatcher;
20 
30  class CNPLConnection :
31  public boost::enable_shared_from_this<CNPLConnection>,
32  private boost::noncopyable
33  {
34  public:
35  enum ProtocolType
36  {
37  NPL = 0,
38  WEBSOCKET = 1,
39  TCP_CUSTOM = 2, // any custom protocol, like google protocol buffer
40  };
41  friend class CNPLDispatcher;
43  typedef std::map<std::string, int> StringMap_Type;
44 
45  ~CNPLConnection();
46 
48  explicit CNPLConnection(boost::asio::io_service& io_service,
49  CNPLConnectionManager& manager, CNPLDispatcher& msg_dispatcher);
50 
52  boost::asio::ip::tcp::socket& socket();
53 
56  void start();
57 
64  void stop(bool bRemoveConnection = true, int nReason = 0);
65 
67  void CloseAfterSend();
68 
71  void connect();
72 
74  CNPLConnectionManager& GetConnectionManager() {return m_connection_manager;};
75 
83  NPLReturnCode SendMessage(const NPLFileName& file_name, const char * code = NULL, int nLength=0, int priority=0);
84 
89  NPLReturnCode SendMessage(const NPLMessage& msg);
90 
95  NPLReturnCode SendMessage(const char* sCommandName, const char* sCommandData);
96 
102  NPLReturnCode SendMessage(NPLMsgOut_ptr& msg);
103 
105  void SetNPLRuntimeAddress(NPLRuntimeAddress_ptr runtime_address);
106 
107  public:
111  virtual void GetStatistics( int &totalIn, int &totalOut );
112 
118  NPLConnectionState GetState() const { return m_state; }
119 
123  const string& GetNID() const;
124 
128  string GetIP();
129 
133  string GetPort();
134 
137  bool SetNID(const char* sNID);
138 
140  void SetAuthenticated(bool bAuthenticated);
141 
146  bool IsAuthenticated() const;
147 
149  bool IsConnected() const;
150 
154  void SetUseCompression(bool bUseCompression);
155 
157  bool IsUseCompression();
158 
165  void SetCompressionLevel(int nLevel);
166  int GetCompressionLevel();
167 
168 
172  void SetCompressionThreshold(int nThreshold);
173  int GetCompressionThreshold();
174 
175 
180  void SetTCPKeepAlive(bool bEnable);
181 
186  void SetKeepAlive(bool bEnable);
187  bool IsKeepAliveEnabled();
188 
195  void EnableIdleTimeout(bool bEnable);
196  bool IsIdleTimeoutEnabled();
197 
199  void SetIdleTimeoutPeriod(int nMilliseconds);
200  int GetIdleTimeoutPeriod();
201 
205  unsigned int GetLastActiveTime();
206 
210  void TickSend();
211 
215  void TickReceive();
216 
221  int CheckIdleTimeout(unsigned int nCurTime);
222 
224  bool HasUnsentData();
225 
227  int GetLogLevel();
228 
230  void SetProtocol(ProtocolType protocolType = ProtocolType::NPL);
231  public:
232  //
233  // In case, one wants to use a different connection data handler, the following interface are provided.
234  //
235 
242  virtual bool handleReceivedData(int bytes_transferred);
243 
247  virtual void handleConnect();
248 
253  virtual void handleDisconnect(int reason);
254 
259  virtual bool handleMessageIn();
260 
261  private:
263  bool handle_websocket_data(int bytes_transferred);
265  bool handle_tcp_custom_data(int bytes_transferred);
266  //
267  // boost io service call backs.
268  //
269 
271  void handle_read(const boost::system::error_code& e,std::size_t bytes_transferred);
272 
274  void handle_write(const boost::system::error_code& e);
275 
277  void handle_stop();
278 
280  void handle_resolve(const boost::system::error_code& err, boost::asio::ip::tcp::resolver::iterator endpoint_iterator);
281 
283  void handle_connect(const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator endpoint_iterator);
284 
286  boost::asio::ip::tcp::socket m_socket;
287 
288  private:
289  typedef boost::array<char, 8192> Buffer_Type;
292 
294  CNPLConnectionManager& m_connection_manager;
295 
297  CNPLDispatcher& m_msg_dispatcher;
298 
300  NPLRuntimeAddress_ptr m_address;
301 
303  Buffer_Type m_buffer;
304 
306  NPLMsgIn m_input_msg;
307 
309  NPLMsgIn_parser m_parser;
310 
312  RingBuffer_Type m_queueOutput;
313 
315  NPLConnectionState m_state;
316 
318  ParaEngine::mutex m_mutex;
319 
321  StringMap_Type m_filename_id_map;
322 
324  uint32 m_totalBytesIn;
326  uint32 m_totalBytesOut;
327 
329  bool m_bDebugConnection;
330 
337  int32 m_nCompressionLevel;
338 
342  int32 m_nCompressionThreshold;
343 
345  bool m_bKeepAlive;
346 
348  bool m_bEnableIdleTimeout;
349 
351  uint32 m_nSendCount;
353  uint32 m_nFinishedCount;
354 
356  bool m_bCloseAfterSend;
357 
359  uint32 m_nIdleTimeoutMS;
360 
362  uint32 m_nLastActiveTime;
363 
365  uint32 m_nStartTime;
366 
368  int32 m_nStopReason;
369 
370  WebSocket::WebSocketReader m_websocket_reader;
371  WebSocket::WebSocketWriter m_websocket_writer;
372  std::vector<byte> m_websocket_input_data;
373  std::vector<byte> m_websocket_out_data;
374 
375  ProtocolType m_protocolType;
376  };
377 
378 
381  { // functor for operator<
382  bool operator()(const NPLConnection_ptr& _Left, const NPLConnection_ptr& _Right) const
383  { // apply operator< to operands
384  return (_Left.get()<_Right.get());
385  }
386  };
387 }
void SetProtocol(ProtocolType protocolType=ProtocolType::NPL)
set transmission protocol, default value is 0.
Definition: NPLConnection.cpp:952
void SetUseCompression(bool bUseCompression)
set whether to use compression for this connection.
Definition: NPLConnection.cpp:132
void TickReceive()
update the last receive or connect time.
Definition: NPLConnection.cpp:180
const string & GetNID() const
Get the NPL runtime address ID if any.
Definition: NPLConnection.cpp:108
define this to enable debugging of NPL code in visual studio
Definition: INPL.h:9
void connect()
connect to the remote NPL runtime address.
Definition: NPLConnection.cpp:561
bool HasUnsentData()
whether there is unsent data.
Definition: NPLConnection.cpp:215
this class serves as an interface between the low level socket interface and NPL message queues...
Definition: NPLDispatcher.h:23
Parser for incoming requests.
Definition: NPLMsgIn_parser.h:118
NPLConnectionState
This describes the possible states of a NPLConnection object.
Definition: NPLTypes.h:80
int GetLogLevel()
get global log level.
Definition: NPLConnection.cpp:220
string GetPort()
Get the TCP IP port if any.
Definition: NPLConnection.cpp:124
void EnableIdleTimeout(bool bEnable)
Enable idle timeout.
Definition: NPLConnection.cpp:82
virtual void handleDisconnect(int reason)
This connection is called when e.g.
Definition: NPLConnection.cpp:728
void TickSend()
update the last send time.
Definition: NPLConnection.cpp:175
void SetKeepAlive(bool bEnable)
enable application level keep alive.
Definition: NPLConnection.cpp:72
A incoming or outgoing connection.
Definition: NPLConnection.h:30
a globally unique name of a NPL file name instance.
Definition: NPLCommon.h:26
void SetTCPKeepAlive(bool bEnable)
set the TCP protocol level keep alive.
Definition: NPLConnection.cpp:64
void SetIdleTimeoutPeriod(int nMilliseconds)
how many milliseconds of inactivity to assume this connection should be timed out.
Definition: NPLConnection.cpp:92
boost::asio::ip::tcp::socket & socket()
Get the socket associated with the connection.
Definition: NPLConnection.cpp:59
A NPL msg received from a socket.
Definition: NPLMsgIn.h:8
CNPLConnectionManager & GetConnectionManager()
return the connection manager.
Definition: NPLConnection.h:74
void SetCompressionLevel(int nLevel)
default to 0, which means no compression.
Definition: NPLConnection.cpp:150
void SetNPLRuntimeAddress(NPLRuntimeAddress_ptr runtime_address)
set the NPL runtime address that this connection connects to.
Definition: NPLConnection.cpp:103
virtual bool handleMessageIn()
handle m_input_msg.
Definition: NPLConnection.cpp:869
void SetCompressionThreshold(int nThreshold)
when the message size is bigger than this number of bytes, we will use m_nCompressionLevel for compre...
Definition: NPLConnection.cpp:160
void stop(bool bRemoveConnection=true, int nReason=0)
Stop all asynchronous operations associated with the connection.
Definition: NPLConnection.cpp:325
unsigned int GetLastActiveTime()
get the last time in milliseconds GetTickCount(), that a send/receive/connect message is transmitted ...
Definition: NPLConnection.cpp:170
CNPLConnection(boost::asio::io_service &io_service, CNPLConnectionManager &manager, CNPLDispatcher &msg_dispatcher)
Construct a connection with the given io_service.
Definition: NPLConnection.cpp:39
bool IsConnected() const
whether the connection is established or not.
Definition: NPLConnection.cpp:937
Definition: inftrees.h:24
a compare class connection ptr
Definition: NPLConnection.h:380
Definition: WebSocketReader.h:9
an NPL message in the message queue.
Definition: NPLMessage.h:32
virtual void handleConnect()
This function is called when e.g.
Definition: NPLConnection.cpp:723
void start()
Start the first asynchronous operation for the connection.
Definition: NPLConnection.cpp:225
bool IsUseCompression()
get whether to use compression for this connection.
Definition: NPLConnection.cpp:145
bool SetNID(const char *sNID)
set nid of this connection.
Definition: NPLConnection.cpp:942
Definition: error.hpp:46
string GetIP()
Get the TCP IP address if any.
Definition: NPLConnection.cpp:116
int CheckIdleTimeout(unsigned int nCurTime)
if any of the connection should be timed out.
Definition: NPLConnection.cpp:185
void CloseAfterSend()
close/stop the connection when all data has been sent
Definition: NPLConnection.cpp:310
cross platform mutex
Definition: mutex.h:95
virtual void GetStatistics(int &totalIn, int &totalOut)
Get statistics about this connection.
Definition: NPLConnection.cpp:580
virtual bool handleReceivedData(int bytes_transferred)
This function is called whenever some data is received from the underlying transport.
Definition: NPLConnection.cpp:804
NPLConnectionState GetState() const
Returns the current connection state.
Definition: NPLConnection.h:118
bool IsAuthenticated() const
whether this connection is authenticated.
Definition: NPLConnection.cpp:932
All incoming and outgoing connection sessions.
Definition: NPLConnectionManager.h:13
void SetAuthenticated(bool bAuthenticated)
set whether this connection is authenticated.
Definition: NPLConnection.cpp:913
Definition: WebSocketWriter.h:9
NPLReturnCode SendMessage(const NPLFileName &file_name, const char *code=NULL, int nLength=0, int priority=0)
Send a message via this connection.
Definition: NPLConnection.cpp:587