SocketServerImpl.h 11 KB

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