UdpServer.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Version : 3.6.1
  5. * Author : Bruce Liang
  6. * Website : http://www.jessma.org
  7. * Project : https://github.com/ldcsaa
  8. * Blog : http://www.cnblogs.com/ldcsaa
  9. * Wiki : http://www.oschina.net/p/hp-socket
  10. * QQ Group : 75375912
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License");
  13. * you may not use this file except in compliance with the License.
  14. * You may obtain a copy of the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS,
  20. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. * See the License for the specific language governing permissions and
  22. * limitations under the License.
  23. */
  24. #pragma once
  25. #include "SocketHelper.h"
  26. #include "../../Common/Src/Event.h"
  27. #include "../../Common/Src/RWLock.h"
  28. #include "../../Common/Src/STLHelper.h"
  29. #include "../../Common/Src/RingBuffer.h"
  30. #include "../../Common/Src/PrivateHeap.h"
  31. class CUdpServer : public IUdpServer
  32. {
  33. public:
  34. CUdpServer(IUdpServerListener* pListener)
  35. : m_pListener (pListener)
  36. , m_hCompletePort (nullptr)
  37. , m_soListen (INVALID_SOCKET)
  38. , m_iRemainPostReceives (0)
  39. , m_enLastError (SE_OK)
  40. , m_enState (SS_STOPPED)
  41. , m_hDetector (nullptr)
  42. , m_enSendPolicy (SP_PACK)
  43. , m_dwMaxConnectionCount (DEFAULT_MAX_CONNECTION_COUNT)
  44. , m_dwWorkerThreadCount (DEFAULT_WORKER_THREAD_COUNT)
  45. , m_dwFreeSocketObjLockTime (DEFAULT_FREE_SOCKETOBJ_LOCK_TIME)
  46. , m_dwFreeSocketObjPool (DEFAULT_FREE_SOCKETOBJ_POOL)
  47. , m_dwFreeBufferObjPool (DEFAULT_FREE_BUFFEROBJ_POOL)
  48. , m_dwFreeSocketObjHold (DEFAULT_FREE_SOCKETOBJ_HOLD)
  49. , m_dwFreeBufferObjHold (DEFAULT_FREE_BUFFEROBJ_HOLD)
  50. , m_dwMaxDatagramSize (DEFAULT_UDP_MAX_DATAGRAM_SIZE)
  51. , m_dwPostReceiveCount (DEFAULT_UDP_POST_RECEIVE_COUNT)
  52. , m_dwDetectAttempts (DEFAULT_UDP_DETECT_ATTEMPTS)
  53. , m_dwDetectInterval (DEFAULT_UDP_DETECT_INTERVAL)
  54. , m_bMarkSilence (TRUE)
  55. {
  56. ASSERT(m_wsSocket.IsValid());
  57. ASSERT(m_pListener);
  58. }
  59. virtual ~CUdpServer()
  60. {
  61. Stop();
  62. }
  63. public:
  64. virtual BOOL Start (LPCTSTR pszBindAddress, USHORT usPort);
  65. virtual BOOL Stop ();
  66. virtual BOOL Send (CONNID dwConnID, const BYTE* pBuffer, int iLength, int iOffset = 0);
  67. virtual BOOL SendPackets(CONNID dwConnID, const WSABUF pBuffers[], int iCount);
  68. virtual BOOL HasStarted () {return m_enState == SS_STARTED || m_enState == SS_STARTING;}
  69. virtual EnServiceState GetState () {return m_enState;}
  70. virtual BOOL Disconnect (CONNID dwConnID, BOOL bForce = TRUE);
  71. virtual BOOL DisconnectLongConnections (DWORD dwPeriod, BOOL bForce = TRUE);
  72. virtual BOOL DisconnectSilenceConnections(DWORD dwPeriod, BOOL bForce = TRUE);
  73. virtual BOOL GetListenAddress (TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
  74. virtual BOOL GetLocalAddress (CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
  75. virtual BOOL GetRemoteAddress (CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
  76. virtual BOOL GetPendingDataLength (CONNID dwConnID, int& iPending);
  77. virtual DWORD GetConnectionCount ();
  78. virtual BOOL GetAllConnectionIDs (CONNID pIDs[], DWORD& dwCount);
  79. virtual BOOL GetConnectPeriod (CONNID dwConnID, DWORD& dwPeriod);
  80. virtual BOOL GetSilencePeriod (CONNID dwConnID, DWORD& dwPeriod);
  81. virtual EnSocketError GetLastError () {return m_enLastError;}
  82. virtual LPCTSTR GetLastErrorDesc () {return ::GetSocketErrorDesc(m_enLastError);}
  83. public:
  84. virtual BOOL SetConnectionExtra(CONNID dwConnID, PVOID pExtra);
  85. virtual BOOL GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra);
  86. virtual void SetSendPolicy (EnSendPolicy enSendPolicy) {m_enSendPolicy = enSendPolicy;}
  87. virtual void SetMaxConnectionCount (DWORD dwMaxConnectionCount) {m_dwMaxConnectionCount = dwMaxConnectionCount;}
  88. virtual void SetWorkerThreadCount (DWORD dwWorkerThreadCount) {m_dwWorkerThreadCount = dwWorkerThreadCount;}
  89. virtual void SetFreeSocketObjLockTime (DWORD dwFreeSocketObjLockTime) {m_dwFreeSocketObjLockTime = dwFreeSocketObjLockTime;}
  90. virtual void SetFreeSocketObjPool (DWORD dwFreeSocketObjPool) {m_dwFreeSocketObjPool = dwFreeSocketObjPool;}
  91. virtual void SetFreeBufferObjPool (DWORD dwFreeBufferObjPool) {m_dwFreeBufferObjPool = dwFreeBufferObjPool;}
  92. virtual void SetFreeSocketObjHold (DWORD dwFreeSocketObjHold) {m_dwFreeSocketObjHold = dwFreeSocketObjHold;}
  93. virtual void SetFreeBufferObjHold (DWORD dwFreeBufferObjHold) {m_dwFreeBufferObjHold = dwFreeBufferObjHold;}
  94. virtual void SetMaxDatagramSize (DWORD dwMaxDatagramSize) {m_dwMaxDatagramSize = dwMaxDatagramSize;}
  95. virtual void SetPostReceiveCount (DWORD dwPostReceiveCount) {m_dwPostReceiveCount = dwPostReceiveCount;}
  96. virtual void SetDetectAttempts (DWORD dwDetectAttempts) {m_dwDetectAttempts = dwDetectAttempts;}
  97. virtual void SetDetectInterval (DWORD dwDetectInterval) {m_dwDetectInterval = dwDetectInterval;}
  98. virtual void SetMarkSilence (BOOL bMarkSilence) {m_bMarkSilence = bMarkSilence;}
  99. virtual EnSendPolicy GetSendPolicy () {return m_enSendPolicy;}
  100. virtual DWORD GetMaxConnectionCount () {return m_dwMaxConnectionCount;}
  101. virtual DWORD GetWorkerThreadCount () {return m_dwWorkerThreadCount;}
  102. virtual DWORD GetFreeSocketObjLockTime () {return m_dwFreeSocketObjLockTime;}
  103. virtual DWORD GetFreeSocketObjPool () {return m_dwFreeSocketObjPool;}
  104. virtual DWORD GetFreeBufferObjPool () {return m_dwFreeBufferObjPool;}
  105. virtual DWORD GetFreeSocketObjHold () {return m_dwFreeSocketObjHold;}
  106. virtual DWORD GetFreeBufferObjHold () {return m_dwFreeBufferObjHold;}
  107. virtual DWORD GetMaxDatagramSize () {return m_dwMaxDatagramSize;}
  108. virtual DWORD GetPostReceiveCount () {return m_dwPostReceiveCount;}
  109. virtual DWORD GetDetectAttempts () {return m_dwDetectAttempts;}
  110. virtual DWORD GetDetectInterval () {return m_dwDetectInterval;}
  111. virtual BOOL IsMarkSilence () {return m_bMarkSilence;}
  112. protected:
  113. virtual EnHandleResult FirePrepareListen(SOCKET soListen)
  114. {return m_pListener->OnPrepareListen(soListen);}
  115. virtual EnHandleResult FireAccept(TUdpSocketObj* pSocketObj)
  116. {
  117. EnHandleResult rs = m_pListener->OnAccept(pSocketObj->connID, &pSocketObj->remoteAddr);
  118. if(rs != HR_ERROR) rs = FireHandShake(pSocketObj);
  119. return rs;
  120. }
  121. virtual EnHandleResult FireHandShake(TUdpSocketObj* pSocketObj)
  122. {return m_pListener->OnHandShake(pSocketObj->connID);}
  123. virtual EnHandleResult FireReceive(TUdpSocketObj* pSocketObj, const BYTE* pData, int iLength)
  124. {return m_pListener->OnReceive(pSocketObj->connID, pData, iLength);}
  125. virtual EnHandleResult FireReceive(TUdpSocketObj* pSocketObj, int iLength)
  126. {return m_pListener->OnReceive(pSocketObj->connID, iLength);}
  127. virtual EnHandleResult FireSend(TUdpSocketObj* pSocketObj, const BYTE* pData, int iLength)
  128. {return m_pListener->OnSend(pSocketObj->connID, pData, iLength);}
  129. virtual EnHandleResult FireClose(TUdpSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
  130. {return m_pListener->OnClose(pSocketObj->connID, enOperation, iErrorCode);}
  131. virtual EnHandleResult FireShutdown()
  132. {return m_pListener->OnShutdown();}
  133. void SetLastError(EnSocketError code, LPCSTR func, int ec);
  134. virtual BOOL CheckParams();
  135. virtual void PrepareStart();
  136. virtual void Reset();
  137. virtual void OnWorkerThreadEnd(DWORD dwThreadID) {}
  138. private:
  139. EnHandleResult TriggerFireAccept(TUdpSocketObj* pSocketObj);
  140. EnHandleResult TriggerFireReceive(TUdpSocketObj* pSocketObj, TUdpBufferObj* pBufferObj);
  141. EnHandleResult TriggerFireSend(TUdpSocketObj* pSocketObj, TUdpBufferObj* pBufferObj);
  142. EnHandleResult TriggerFireClose(TUdpSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode);
  143. protected:
  144. BOOL SetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID pExtra);
  145. BOOL GetConnectionExtra(TUdpSocketObj* pSocketObj, PVOID* ppExtra);
  146. BOOL SetConnectionReserved(CONNID dwConnID, PVOID pReserved);
  147. BOOL GetConnectionReserved(CONNID dwConnID, PVOID* ppReserved);
  148. BOOL SetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID pReserved);
  149. BOOL GetConnectionReserved(TUdpSocketObj* pSocketObj, PVOID* ppReserved);
  150. BOOL SetConnectionReserved2(CONNID dwConnID, PVOID pReserved2);
  151. BOOL GetConnectionReserved2(CONNID dwConnID, PVOID* ppReserved2);
  152. BOOL SetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID pReserved2);
  153. BOOL GetConnectionReserved2(TUdpSocketObj* pSocketObj, PVOID* ppReserved2);
  154. private:
  155. static UINT WINAPI WorkerThreadProc(LPVOID pv);
  156. static UINT WINAPI DetecotrThreadProc(LPVOID pv);
  157. private:
  158. BOOL CheckStarting();
  159. BOOL CheckStoping();
  160. BOOL CreateListenSocket(LPCTSTR pszBindAddress, USHORT usPort);
  161. BOOL CreateCompletePort();
  162. BOOL CreateWorkerThreads();
  163. BOOL CreateDetectorThread();
  164. BOOL StartAccept();
  165. void CloseListenSocket();
  166. void WaitForPostReceiveRelease();
  167. void DisconnectClientSocket();
  168. void WaitForClientSocketClose();
  169. void ReleaseClientSocket();
  170. void ReleaseFreeSocket();
  171. void ReleaseFreeBuffer();
  172. void WaitForWorkerThreadEnd();
  173. void WaitForDetectorThreadEnd();
  174. void CloseCompletePort();
  175. TUdpBufferObj* GetFreeBufferObj(int iLen = -1);
  176. TUdpSocketObj* GetFreeSocketObj(CONNID dwConnID);
  177. void AddFreeBufferObj(TUdpBufferObj* pBufferObj);
  178. void AddFreeSocketObj(CONNID dwConnID, EnSocketCloseFlag enFlag = SCF_NONE, EnSocketOperation enOperation = SO_UNKNOWN, int iErrorCode = 0);
  179. void AddFreeSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag = SCF_NONE, EnSocketOperation enOperation = SO_UNKNOWN, int iErrorCode = 0);
  180. TUdpSocketObj* CreateSocketObj();
  181. void DeleteSocketObj(TUdpSocketObj* pSocketObj);
  182. BOOL InvalidSocketObj(TUdpSocketObj* pSocketObj);
  183. void ReleaseGCSocketObj(BOOL bForce = FALSE);
  184. void AddClientSocketObj(CONNID dwConnID, TUdpSocketObj* pSocketObj);
  185. void CloseClientSocketObj(TUdpSocketObj* pSocketObj, EnSocketCloseFlag enFlag = SCF_NONE, EnSocketOperation enOperation = SO_UNKNOWN, int iErrorCode = 0);
  186. TUdpSocketObj* FindSocketObj(CONNID dwConnID);
  187. CONNID FindConnectionID(SOCKADDR_IN* pAddr);
  188. private:
  189. EnIocpAction CheckIocpCommand(OVERLAPPED* pOverlapped, DWORD dwBytes, ULONG_PTR ulCompKey);
  190. void ForceDisconnect(CONNID dwConnID);
  191. void HandleIo (CONNID dwConnID, TUdpBufferObj* pBufferObj, DWORD dwBytes, DWORD dwErrorCode);
  192. void HandleError (CONNID dwConnID, TUdpBufferObj* pBufferObj, DWORD dwErrorCode);
  193. void HandleZeroBytes(CONNID dwConnID, TUdpBufferObj* pBufferObj);
  194. CONNID HandleAccept (TUdpBufferObj* pBufferObj);
  195. void HandleSend (CONNID dwConnID, TUdpBufferObj* pBufferObj);
  196. void HandleReceive (CONNID dwConnID, TUdpBufferObj* pBufferObj);
  197. int SendInternal(CONNID dwConnID, const BYTE* pBuffer, int iLength);
  198. int SendPack (TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  199. int SendSafe (TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  200. int SendDirect (TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  201. int CatAndPost (TUdpSocketObj* pSocketObj, const BYTE* pBuffer, int iLength, BOOL isPostSend);
  202. BOOL DoAccept ();
  203. int DoReceive (TUdpBufferObj* pBufferObj);
  204. int DoSend (CONNID dwConnID);
  205. int DoSend (TUdpSocketObj* pSocketObj);
  206. int DoSendPack (TUdpSocketObj* pSocketObj);
  207. int DoSendSafe (TUdpSocketObj* pSocketObj);
  208. int SendItem (TUdpSocketObj* pSocketObj);
  209. void DetectConnections ();
  210. BOOL SendDetectPackage (CONNID dwConnID, TUdpSocketObj* pSocketObj);
  211. BOOL NeedDetectorThread () {return m_dwDetectAttempts > 0 && m_dwDetectInterval > 0;}
  212. private:
  213. EnSendPolicy m_enSendPolicy;
  214. DWORD m_dwMaxConnectionCount;
  215. DWORD m_dwWorkerThreadCount;
  216. DWORD m_dwFreeSocketObjLockTime;
  217. DWORD m_dwFreeSocketObjPool;
  218. DWORD m_dwFreeBufferObjPool;
  219. DWORD m_dwFreeSocketObjHold;
  220. DWORD m_dwFreeBufferObjHold;
  221. DWORD m_dwMaxDatagramSize;
  222. DWORD m_dwPostReceiveCount;
  223. DWORD m_dwDetectAttempts;
  224. DWORD m_dwDetectInterval;
  225. BOOL m_bMarkSilence;
  226. private:
  227. CInitSocket m_wsSocket;
  228. private:
  229. IUdpServerListener* m_pListener;
  230. SOCKET m_soListen;
  231. HANDLE m_hCompletePort;
  232. EnServiceState m_enState;
  233. EnSocketError m_enLastError;
  234. HANDLE m_hDetector;
  235. vector<HANDLE> m_vtWorkerThreads;
  236. CPrivateHeap m_phSocket;
  237. CUdpBufferObjPool m_bfObjPool;
  238. CSpinGuard m_csState;
  239. CCriSec m_csAccept;
  240. CEvt m_evDetector;
  241. TUdpSocketObjPtrPool m_bfActiveSockets;
  242. CRWLock m_csClientSocket;
  243. TSockAddrMap m_mpClientAddr;
  244. TUdpSocketObjPtrList m_lsFreeSocket;
  245. TUdpSocketObjPtrQueue m_lsGCSocket;
  246. volatile long m_iRemainPostReceives;
  247. };