SocketServerImpl.h 10 KB

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