SocketServerImpl.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #ifndef __SOCKETSERVERIMPL_20160228__
  2. #define __SOCKETSERVERIMPL_20160228__
  3. #pragma once
  4. #pragma warning(push)
  5. #pragma warning(disable:4995)
  6. #include <vector>
  7. #include <list>
  8. #pragma warning(pop)
  9. #include "CritSection.h"
  10. #include "ThreadPool.hpp"
  11. #include "SocketHandle.h"
  12. typedef std::list<SOCKET> SocketList;
  13. /************************************************************************/
  14. /* Copyright (C), 2016-2020, [IT], 保留所有权利;
  15. /* 模 块 名:ISocketServerHandler;
  16. /* 描 述:Event handler that SocketServerImpl<T> must implement;
  17. /* This class is not required, you can do the same thing as long your class exposes these functions.
  18. /* (These functions are not pure to save you some typing)
  19. /*
  20. /* 版 本:[V];
  21. /* 作 者:[IT];
  22. /* 日 期:[2/23/2016];
  23. /*
  24. /*
  25. /* 注 意:;
  26. /*
  27. /* 修改记录:[IT];
  28. /* 修改日期:;
  29. /* 修改版本:;
  30. /* 修改内容:;
  31. /************************************************************************/
  32. class ISocketServerHandler
  33. {
  34. public:
  35. virtual void OnThreadBegin(CSocketHandle* ) {}
  36. virtual void OnThreadExit(CSocketHandle* ) {}
  37. virtual void OnThreadLoopEnter(CSocketHandle* ) {}
  38. virtual void OnThreadLoopLeave(CSocketHandle* ) {}
  39. virtual void OnAddConnection(CSocketHandle* , SOCKET ) {}
  40. virtual void OnRemoveConnection(CSocketHandle* , SOCKET ) {}
  41. virtual void OnDataReceived(CSocketHandle* , const SOCKET sClient, const BYTE* pData, DWORD dwCount, const SockAddrIn&, BYTE **pendingbuf, unsigned int& npendingSize, unsigned int& ncursize ) {}
  42. virtual void OnConnectionFailure(CSocketHandle*, SOCKET) {}
  43. virtual void OnConnectionDropped(CSocketHandle* ) {}
  44. virtual void OnConnectionError(CSocketHandle* , DWORD ) {}
  45. };
  46. /************************************************************************/
  47. /* Copyright (C), 2016-2020, [IT], 保留所有权利;
  48. /* 模 块 名:SocketServerImpl<T, tBufferSize>;
  49. /* 描 述:Because <typename T> may refer to any class of your choosing,Server Communication wrapper;
  50. /*
  51. /* 版 本:[V];
  52. /* 作 者:[IT];
  53. /* 日 期:[2/23/2016];
  54. /*
  55. /*
  56. /* 注 意:;
  57. /*
  58. /* 修改记录:[IT];
  59. /* 修改日期:;
  60. /* 修改版本:;
  61. /* 修改内容:;
  62. /************************************************************************/
  63. template <typename T, size_t tBufferSize = 1024*64>
  64. class SocketServerImpl
  65. {
  66. typedef SocketServerImpl<T, tBufferSize> thisClass;
  67. public:
  68. SocketServerImpl()
  69. : _pInterface(0)
  70. , _thread(0)
  71. {
  72. }
  73. void SetInterface(T* pInterface)
  74. {
  75. ::InterlockedExchangePointer(reinterpret_cast<void**>(&_pInterface), pInterface);
  76. }
  77. operator CSocketHandle*() throw()
  78. {
  79. return( &_socket );
  80. }
  81. CSocketHandle* operator->() throw()
  82. {
  83. return( &_socket );
  84. }
  85. bool IsOpen() const
  86. {
  87. return _socket.IsOpen();
  88. }
  89. bool CreateSocket(LPCTSTR pszHost, LPCTSTR pszServiceName, int nFamily, int nType, UINT uOptions = 0)
  90. {
  91. return _socket.CreateSocket(pszHost, pszServiceName, nFamily, nType, uOptions);
  92. }
  93. void Close()
  94. {
  95. _socket.Close();
  96. }
  97. DWORD Read(LPBYTE lpBuffer, DWORD dwSize, LPSOCKADDR lpAddrIn = NULL, DWORD dwTimeout = INFINITE)
  98. {
  99. return _socket.Read(lpBuffer, dwSize, lpAddrIn, dwTimeout);
  100. }
  101. DWORD Write(const LPBYTE lpBuffer, DWORD dwCount, const LPSOCKADDR lpAddrIn = NULL, DWORD dwTimeout = INFINITE)
  102. {
  103. return _socket.Write(lpBuffer, dwCount, lpAddrIn, dwTimeout);
  104. }
  105. const SocketList& GetSocketList() const
  106. {
  107. // direct access! - use Lock/Unlock to protect
  108. return _sockets;
  109. }
  110. bool Lock()
  111. {
  112. return _critSection.Lock();
  113. }
  114. bool Unlock()
  115. {
  116. return _critSection.Unlock();
  117. }
  118. void ResetConnectionList()
  119. {
  120. AutoThreadSection aSection(&_critSection);
  121. _sockets.clear();
  122. }
  123. size_t GetConnectionCount() const
  124. {
  125. AutoThreadSection aSection(&_critSection);
  126. return _sockets.size();
  127. }
  128. void AddConnection(SOCKET sock)
  129. {
  130. AutoThreadSection aSection(&_critSection);
  131. _sockets.push_back( sock );
  132. }
  133. void RemoveConnection(SOCKET sock)
  134. {
  135. AutoThreadSection aSection(&_critSection);
  136. _sockets.remove( sock );
  137. }
  138. bool CloseConnection(SOCKET sock)
  139. {
  140. return CSocketHandle::ShutdownConnection( sock );
  141. }
  142. void CloseAllConnections();
  143. bool StartServer(LPCTSTR pszHost, LPCTSTR pszServiceName, int nFamily, int nType, UINT uOptions = 0);
  144. void Terminate(DWORD dwTimeout = INFINITE);
  145. static bool IsConnectionDropped(DWORD dwError);
  146. protected:
  147. void Run();
  148. void OnConnection(ULONG_PTR s);
  149. static DWORD WINAPI SocketServerProc(thisClass* _this);
  150. T* _pInterface;
  151. HANDLE _thread;
  152. ThreadSection _critSection;
  153. CSocketHandle _socket;
  154. SocketList _sockets;
  155. };
  156. template <typename T, size_t tBufferSize>
  157. void SocketServerImpl<T, tBufferSize>::CloseAllConnections()
  158. {
  159. AutoThreadSection aSection(&_critSection);
  160. if ( !_sockets.empty() )
  161. {
  162. // NOTE(elaurentin): this function closes all connections but handles are kept inside of list
  163. // (socket handles are removed by the pooling thread)
  164. SocketList::iterator iter;
  165. for(iter = _sockets.begin(); iter != _sockets.end(); ++iter)
  166. {
  167. CloseConnection( (*iter) );
  168. }
  169. }
  170. }
  171. template <typename T, size_t tBufferSize>
  172. bool SocketServerImpl<T, tBufferSize>::StartServer(LPCTSTR pszHost, LPCTSTR pszServiceName, int nFamily, int nType, UINT uOptions)
  173. {
  174. // must be closed first...
  175. if ( IsOpen() ) return false;
  176. bool result = false;
  177. result = _socket.CreateSocket(pszHost, pszServiceName, nFamily, nType, uOptions);
  178. if ( result )
  179. {
  180. _thread = AtlCreateThread(SocketServerProc, this);
  181. if ( _thread == NULL )
  182. {
  183. DWORD dwError = GetLastError();
  184. _socket.Close();
  185. SetLastError(dwError);
  186. result = false;
  187. }
  188. }
  189. return result;
  190. }
  191. template <typename T, size_t tBufferSize>
  192. DWORD WINAPI SocketServerImpl<T, tBufferSize>::SocketServerProc(thisClass* _this)
  193. {
  194. if ( _this != NULL )
  195. {
  196. _this->Run();
  197. }
  198. return 0;
  199. }
  200. template <typename T, size_t tBufferSize>
  201. void SocketServerImpl<T, tBufferSize>::Run()
  202. {
  203. _ASSERTE( _pInterface != NULL && "Need an interface to pass events");
  204. SOCKET sock = _socket.GetSocket();
  205. int type = _socket.GetSocketType();
  206. // Notification: OnThreadBegin
  207. if ( _pInterface != NULL ) {
  208. _pInterface->OnThreadBegin(*this);
  209. }
  210. if (type == SOCK_STREAM)
  211. {
  212. // In TCP mode, we need one thread per connection
  213. while( _socket.IsOpen() )
  214. {
  215. SOCKET newSocket = CSocketHandle::WaitForConnection(sock);
  216. if (!_socket.IsOpen())
  217. break;
  218. // run a new client thread for each connection
  219. // report failure if not a valid socket or threadpool failed
  220. if ((newSocket == INVALID_SOCKET) ||
  221. !ThreadPool::QueueWorkItem(&SocketServerImpl<T, tBufferSize>::OnConnection,
  222. this,
  223. static_cast<ULONG_PTR>(newSocket))
  224. )
  225. {
  226. // Notification: OnConnectionFailure
  227. if ( _pInterface != NULL ) {
  228. _pInterface->OnConnectionFailure(*this, newSocket);
  229. }
  230. }
  231. }
  232. // close all connections
  233. CloseAllConnections();
  234. }
  235. else
  236. {
  237. // UDP - only one instance
  238. OnConnection( sock );
  239. }
  240. // Notification: OnThreadExit
  241. if ( _pInterface != NULL ) {
  242. _pInterface->OnThreadExit(*this);
  243. }
  244. }
  245. template <typename T, size_t tBufferSize>
  246. void SocketServerImpl<T, tBufferSize>::OnConnection(ULONG_PTR s)
  247. {
  248. SockAddrIn addrIn;
  249. std::vector<unsigned char> data;
  250. data.resize( tBufferSize );
  251. DWORD dwRead;
  252. DWORD dwError;
  253. SOCKET sock = static_cast<SOCKET>(static_cast<ULONG>(s));
  254. CSocketHandle sockHandle;
  255. sockHandle.Attach(sock);
  256. sockHandle.GetPeerName( addrIn );
  257. int type = sockHandle.GetSocketType();
  258. // Notification: OnThreadLoopEnter
  259. if ( _pInterface != NULL ) {
  260. _pInterface->OnThreadLoopEnter(*this);
  261. }
  262. if (type == SOCK_STREAM) {
  263. AddConnection( sock );
  264. // Notification: OnAddConnection
  265. if ( _pInterface != NULL ) {
  266. _pInterface->OnAddConnection(*this, sock);
  267. }
  268. }
  269. if (type == SOCK_STREAM) {
  270. _socket.GetPeerName( addrIn );
  271. }
  272. // Connection loop
  273. while ( sockHandle.IsOpen() )
  274. {
  275. if (type == SOCK_STREAM)
  276. {
  277. dwRead = sockHandle.Read(&data[0], tBufferSize, NULL, INFINITE);
  278. }
  279. else
  280. {
  281. dwRead = sockHandle.Read(&data[0], tBufferSize, addrIn, INFINITE);
  282. }
  283. if ( ( dwRead != -1L ) && (dwRead > 0))
  284. {
  285. // Notification: OnDataReceived
  286. if ( _pInterface != NULL ) {
  287. _pInterface->OnDataReceived(*this, &data[0], dwRead, addrIn);
  288. }
  289. }
  290. else if (type == SOCK_STREAM && dwRead == 0L )
  291. {
  292. // connection broken
  293. if ( _pInterface != NULL ) {
  294. _pInterface->OnConnectionDropped(*this);
  295. }
  296. break;
  297. }
  298. else if ( dwRead == -1L)
  299. {
  300. dwError = GetLastError();
  301. if ( _pInterface != NULL )
  302. {
  303. if (IsConnectionDropped( dwError) ) {
  304. // Notification: OnConnectionDropped
  305. if (type == SOCK_STREAM || (dwError == WSAENOTSOCK || dwError == WSAENETDOWN))
  306. {
  307. _pInterface->OnConnectionDropped(*this);
  308. break;
  309. }
  310. }
  311. // Notification: OnConnectionError
  312. _pInterface->OnConnectionError(*this, dwError);
  313. }
  314. else {
  315. break;
  316. }
  317. }
  318. }
  319. // remove this connection from our list
  320. if (type == SOCK_STREAM) {
  321. RemoveConnection( sock );
  322. // Notification: OnRemoveConnection
  323. if ( _pInterface != NULL ) {
  324. _pInterface->OnRemoveConnection(*this, sock);
  325. }
  326. }
  327. // Detach or Close this socket (TCP-mode only)
  328. if (type != SOCK_STREAM ) {
  329. sockHandle.Detach();
  330. }
  331. data.clear();
  332. // Notification: OnThreadLoopLeave
  333. if ( _pInterface != NULL ) {
  334. _pInterface->OnThreadLoopLeave(*this);
  335. }
  336. }
  337. template <typename T, size_t tBufferSize>
  338. void SocketServerImpl<T, tBufferSize>::Terminate(DWORD dwTimeout /*= INFINITE*/)
  339. {
  340. _socket.Close();
  341. if ( _thread != NULL )
  342. {
  343. if ( WaitForSingleObject(_thread, dwTimeout) == WAIT_TIMEOUT ) {
  344. TerminateThread(_thread, 1);
  345. }
  346. CloseHandle(_thread);
  347. _thread = NULL;
  348. }
  349. }
  350. template <typename T, size_t tBufferSize>
  351. bool SocketServerImpl<T, tBufferSize>::IsConnectionDropped(DWORD dwError)
  352. {
  353. // see: winerror.h for definition
  354. switch( dwError )
  355. {
  356. case WSAENOTSOCK:
  357. case WSAENETDOWN:
  358. case WSAENETUNREACH:
  359. case WSAENETRESET:
  360. case WSAECONNABORTED:
  361. case WSAECONNRESET:
  362. case WSAESHUTDOWN:
  363. case WSAEHOSTDOWN:
  364. case WSAEHOSTUNREACH:
  365. return true;
  366. default:
  367. break;
  368. }
  369. return false;
  370. }
  371. #endif // __SOCKETSERVERIMPL_20160228__