开源的socket服务端客户端,支持C# C++

TcpAgent.h 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Version : 4.1.3
  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/STLHelper.h"
  28. #include "../../Common/Src/RingBuffer.h"
  29. #include "../../Common/Src/PrivateHeap.h"
  30. class CTcpAgent : public ITcpAgent
  31. {
  32. public:
  33. virtual BOOL Start (LPCTSTR lpszBindAddress = nullptr, BOOL bAsyncConnect = TRUE);
  34. virtual BOOL Stop ();
  35. virtual BOOL Connect(LPCTSTR lpszRemoteAddress, USHORT usPort, CONNID* pdwConnID = nullptr);
  36. virtual BOOL Send (CONNID dwConnID, const BYTE* pBuffer, int iLength, int iOffset = 0);
  37. virtual BOOL SendSmallFile (CONNID dwConnID, LPCTSTR lpszFileName, const LPWSABUF pHead = nullptr, const LPWSABUF pTail = nullptr);
  38. virtual BOOL SendPackets (CONNID dwConnID, const WSABUF pBuffers[], int iCount) {return DoSendPackets(dwConnID, pBuffers, iCount);}
  39. virtual BOOL HasStarted () {return m_enState == SS_STARTED || m_enState == SS_STARTING;}
  40. virtual EnServiceState GetState () {return m_enState;}
  41. virtual BOOL Disconnect (CONNID dwConnID, BOOL bForce = TRUE);
  42. virtual BOOL DisconnectLongConnections (DWORD dwPeriod, BOOL bForce = TRUE);
  43. virtual BOOL DisconnectSilenceConnections(DWORD dwPeriod, BOOL bForce = TRUE);
  44. virtual BOOL GetLocalAddress (CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
  45. virtual BOOL GetRemoteAddress (CONNID dwConnID, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
  46. virtual BOOL GetRemoteHost (CONNID dwConnID, TCHAR lpszHost[], int& iHostLen, USHORT& usPort);
  47. virtual BOOL GetPendingDataLength (CONNID dwConnID, int& iPending);
  48. virtual DWORD GetConnectionCount ();
  49. virtual BOOL GetAllConnectionIDs (CONNID pIDs[], DWORD& dwCount);
  50. virtual BOOL GetConnectPeriod (CONNID dwConnID, DWORD& dwPeriod);
  51. virtual BOOL GetSilencePeriod (CONNID dwConnID, DWORD& dwPeriod);
  52. virtual EnSocketError GetLastError () {return m_enLastError;}
  53. virtual LPCTSTR GetLastErrorDesc () {return ::GetSocketErrorDesc(m_enLastError);}
  54. public:
  55. virtual BOOL SetConnectionExtra(CONNID dwConnID, PVOID pExtra);
  56. virtual BOOL GetConnectionExtra(CONNID dwConnID, PVOID* ppExtra);
  57. virtual void SetSendPolicy (EnSendPolicy enSendPolicy) {m_enSendPolicy = enSendPolicy;}
  58. virtual void SetMaxConnectionCount (DWORD dwMaxConnectionCount) {m_dwMaxConnectionCount = dwMaxConnectionCount;}
  59. virtual void SetWorkerThreadCount (DWORD dwWorkerThreadCount) {m_dwWorkerThreadCount = dwWorkerThreadCount;}
  60. virtual void SetSocketBufferSize (DWORD dwSocketBufferSize) {m_dwSocketBufferSize = dwSocketBufferSize;}
  61. virtual void SetFreeSocketObjLockTime (DWORD dwFreeSocketObjLockTime) {m_dwFreeSocketObjLockTime = dwFreeSocketObjLockTime;}
  62. virtual void SetFreeSocketObjPool (DWORD dwFreeSocketObjPool) {m_dwFreeSocketObjPool = dwFreeSocketObjPool;}
  63. virtual void SetFreeBufferObjPool (DWORD dwFreeBufferObjPool) {m_dwFreeBufferObjPool = dwFreeBufferObjPool;}
  64. virtual void SetFreeSocketObjHold (DWORD dwFreeSocketObjHold) {m_dwFreeSocketObjHold = dwFreeSocketObjHold;}
  65. virtual void SetFreeBufferObjHold (DWORD dwFreeBufferObjHold) {m_dwFreeBufferObjHold = dwFreeBufferObjHold;}
  66. virtual void SetKeepAliveTime (DWORD dwKeepAliveTime) {m_dwKeepAliveTime = dwKeepAliveTime;}
  67. virtual void SetKeepAliveInterval (DWORD dwKeepAliveInterval) {m_dwKeepAliveInterval = dwKeepAliveInterval;}
  68. virtual void SetReuseAddress (BOOL bReuseAddress) {m_bReuseAddress = bReuseAddress;}
  69. virtual void SetMarkSilence (BOOL bMarkSilence) {m_bMarkSilence = bMarkSilence;}
  70. virtual EnSendPolicy GetSendPolicy () {return m_enSendPolicy;}
  71. virtual DWORD GetMaxConnectionCount () {return m_dwMaxConnectionCount;}
  72. virtual DWORD GetWorkerThreadCount () {return m_dwWorkerThreadCount;}
  73. virtual DWORD GetSocketBufferSize () {return m_dwSocketBufferSize;}
  74. virtual DWORD GetFreeSocketObjLockTime () {return m_dwFreeSocketObjLockTime;}
  75. virtual DWORD GetFreeSocketObjPool () {return m_dwFreeSocketObjPool;}
  76. virtual DWORD GetFreeBufferObjPool () {return m_dwFreeBufferObjPool;}
  77. virtual DWORD GetFreeSocketObjHold () {return m_dwFreeSocketObjHold;}
  78. virtual DWORD GetFreeBufferObjHold () {return m_dwFreeBufferObjHold;}
  79. virtual DWORD GetKeepAliveTime () {return m_dwKeepAliveTime;}
  80. virtual DWORD GetKeepAliveInterval () {return m_dwKeepAliveInterval;}
  81. virtual BOOL IsReuseAddress () {return m_bReuseAddress;}
  82. virtual BOOL IsMarkSilence () {return m_bMarkSilence;}
  83. protected:
  84. virtual EnHandleResult FirePrepareConnect(CONNID dwConnID, SOCKET socket)
  85. {return DoFirePrepareConnect(dwConnID, socket);}
  86. virtual EnHandleResult FireConnect(TSocketObj* pSocketObj)
  87. {
  88. EnHandleResult rs = DoFireConnect(pSocketObj);
  89. if(rs != HR_ERROR) rs = FireHandShake(pSocketObj);
  90. return rs;
  91. }
  92. virtual EnHandleResult FireHandShake(TSocketObj* pSocketObj)
  93. {return DoFireHandShake(pSocketObj);}
  94. virtual EnHandleResult FireReceive(TSocketObj* pSocketObj, const BYTE* pData, int iLength)
  95. {return DoFireReceive(pSocketObj, pData, iLength);}
  96. virtual EnHandleResult FireReceive(TSocketObj* pSocketObj, int iLength)
  97. {return DoFireReceive(pSocketObj, iLength);}
  98. virtual EnHandleResult FireSend(TSocketObj* pSocketObj, const BYTE* pData, int iLength)
  99. {return DoFireSend(pSocketObj, pData, iLength);}
  100. virtual EnHandleResult FireClose(TSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
  101. {return DoFireClose(pSocketObj, enOperation, iErrorCode);}
  102. virtual EnHandleResult FireShutdown()
  103. {return DoFireShutdown();}
  104. virtual EnHandleResult DoFirePrepareConnect(CONNID dwConnID, SOCKET socket)
  105. {return m_pListener->OnPrepareConnect(this, dwConnID, socket);}
  106. virtual EnHandleResult DoFireConnect(TSocketObj* pSocketObj)
  107. {return m_pListener->OnConnect(this, pSocketObj->connID);}
  108. virtual EnHandleResult DoFireHandShake(TSocketObj* pSocketObj)
  109. {return m_pListener->OnHandShake(this, pSocketObj->connID);}
  110. virtual EnHandleResult DoFireReceive(TSocketObj* pSocketObj, const BYTE* pData, int iLength)
  111. {return m_pListener->OnReceive(this, pSocketObj->connID, pData, iLength);}
  112. virtual EnHandleResult DoFireReceive(TSocketObj* pSocketObj, int iLength)
  113. {return m_pListener->OnReceive(this, pSocketObj->connID, iLength);}
  114. virtual EnHandleResult DoFireSend(TSocketObj* pSocketObj, const BYTE* pData, int iLength)
  115. {return m_pListener->OnSend(this, pSocketObj->connID, pData, iLength);}
  116. virtual EnHandleResult DoFireClose(TSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode)
  117. {return m_pListener->OnClose(this, pSocketObj->connID, enOperation, iErrorCode);}
  118. virtual EnHandleResult DoFireShutdown()
  119. {return m_pListener->OnShutdown(this);}
  120. void SetLastError(EnSocketError code, LPCSTR func, int ec);
  121. virtual BOOL CheckParams();
  122. virtual void PrepareStart();
  123. virtual void Reset();
  124. virtual void OnWorkerThreadEnd(DWORD dwThreadID) {}
  125. BOOL DoSendPackets(CONNID dwConnID, const WSABUF pBuffers[], int iCount);
  126. BOOL DoSendPackets(TSocketObj* pSocketObj, const WSABUF pBuffers[], int iCount);
  127. TSocketObj* FindSocketObj(CONNID dwConnID);
  128. BOOL GetRemoteHost(CONNID dwConnID, LPCSTR* lpszHost, USHORT* pusPort = nullptr);
  129. private:
  130. EnHandleResult TriggerFireConnect(TSocketObj* pSocketObj);
  131. EnHandleResult TriggerFireReceive(TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  132. EnHandleResult TriggerFireSend(TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  133. EnHandleResult TriggerFireClose(TSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode);
  134. protected:
  135. BOOL SetConnectionExtra(TSocketObj* pSocketObj, PVOID pExtra);
  136. BOOL GetConnectionExtra(TSocketObj* pSocketObj, PVOID* ppExtra);
  137. BOOL SetConnectionReserved(CONNID dwConnID, PVOID pReserved);
  138. BOOL GetConnectionReserved(CONNID dwConnID, PVOID* ppReserved);
  139. BOOL SetConnectionReserved(TSocketObj* pSocketObj, PVOID pReserved);
  140. BOOL GetConnectionReserved(TSocketObj* pSocketObj, PVOID* ppReserved);
  141. BOOL SetConnectionReserved2(CONNID dwConnID, PVOID pReserved2);
  142. BOOL GetConnectionReserved2(CONNID dwConnID, PVOID* ppReserved2);
  143. BOOL SetConnectionReserved2(TSocketObj* pSocketObj, PVOID pReserved2);
  144. BOOL GetConnectionReserved2(TSocketObj* pSocketObj, PVOID* ppReserved2);
  145. private:
  146. BOOL CheckStarting();
  147. BOOL CheckStoping();
  148. BOOL ParseBindAddress(LPCTSTR lpszBindAddress);
  149. BOOL CreateCompletePort();
  150. BOOL CreateWorkerThreads();
  151. void DisconnectClientSocket();
  152. void WaitForClientSocketClose();
  153. void ReleaseClientSocket();
  154. void ReleaseFreeSocket();
  155. void ReleaseFreeBuffer();
  156. void WaitForWorkerThreadEnd();
  157. void CloseCompletePort();
  158. TBufferObj* GetFreeBufferObj(int iLen = -1);
  159. TSocketObj* GetFreeSocketObj(CONNID dwConnID, SOCKET soClient);
  160. void AddFreeBufferObj(TBufferObj* pBufferObj);
  161. void AddFreeSocketObj(TSocketObj* pSocketObj, EnSocketCloseFlag enFlag = SCF_NONE, EnSocketOperation enOperation = SO_UNKNOWN, int iErrorCode = 0);
  162. TSocketObj* CreateSocketObj();
  163. void DeleteSocketObj(TSocketObj* pSocketObj);
  164. BOOL InvalidSocketObj(TSocketObj* pSocketObj);
  165. void ReleaseGCSocketObj(BOOL bForce = FALSE);
  166. void AddClientSocketObj(CONNID dwConnID, TSocketObj* pSocketObj);
  167. void CloseClientSocketObj(TSocketObj* pSocketObj, EnSocketCloseFlag enFlag = SCF_NONE, EnSocketOperation enOperation = SO_UNKNOWN, int iErrorCode = 0, int iShutdownFlag = SD_SEND);
  168. private:
  169. static UINT WINAPI WorkerThreadProc(LPVOID pv);
  170. EnIocpAction CheckIocpCommand(OVERLAPPED* pOverlapped, DWORD dwBytes, ULONG_PTR ulCompKey);
  171. DWORD CreateClientSocket( LPCTSTR lpszRemoteAddress, USHORT usPort, SOCKET& soClient, SOCKADDR_IN& addr);
  172. DWORD PrepareConnect (CONNID& dwConnID, SOCKET soClient);
  173. DWORD ConnectToServer (CONNID dwConnID, LPCTSTR lpszRemoteAddress, USHORT usPort, SOCKET soClient, const SOCKADDR_IN& addr);
  174. void ForceDisconnect (CONNID dwConnID);
  175. void HandleIo (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj, DWORD dwBytes, DWORD dwErrorCode);
  176. void HandleError (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj, DWORD dwErrorCode);
  177. void HandleConnect (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  178. void HandleSend (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  179. void HandleReceive (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  180. int SendInternal(TSocketObj* pSocketObj, const WSABUF pBuffers[], int iCount);
  181. int SendPack (TSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  182. int SendSafe (TSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  183. int SendDirect (TSocketObj* pSocketObj, const BYTE* pBuffer, int iLength);
  184. int CatAndPost (TSocketObj* pSocketObj, const BYTE* pBuffer, int iLength, BOOL isPostSend);
  185. int DoConnect (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  186. int DoReceive (CONNID dwConnID, TSocketObj* pSocketObj, TBufferObj* pBufferObj);
  187. int DoSend (CONNID dwConnID);
  188. int DoSend (TSocketObj* pSocketObj);
  189. int DoSendPack (TSocketObj* pSocketObj);
  190. int DoSendSafe (TSocketObj* pSocketObj);
  191. int SendItem (TSocketObj* pSocketObj);
  192. void CheckError (TSocketObj* pSocketObj, EnSocketOperation enOperation, int iErrorCode);
  193. public:
  194. CTcpAgent(ITcpAgentListener* pListener)
  195. : m_pListener (pListener)
  196. , m_hCompletePort (nullptr)
  197. , m_pfnConnectEx (nullptr)
  198. , m_pfnDisconnectEx (nullptr)
  199. , m_enLastError (SE_OK)
  200. , m_enState (SS_STOPPED)
  201. , m_bAsyncConnect (TRUE)
  202. , m_enSendPolicy (SP_PACK)
  203. , m_dwMaxConnectionCount (DEFAULT_MAX_CONNECTION_COUNT)
  204. , m_dwWorkerThreadCount (DEFAULT_WORKER_THREAD_COUNT)
  205. , m_dwSocketBufferSize (DEFAULT_TCP_SOCKET_BUFFER_SIZE)
  206. , m_dwFreeSocketObjLockTime (DEFAULT_FREE_SOCKETOBJ_LOCK_TIME)
  207. , m_dwFreeSocketObjPool (DEFAULT_FREE_SOCKETOBJ_POOL)
  208. , m_dwFreeBufferObjPool (DEFAULT_FREE_BUFFEROBJ_POOL)
  209. , m_dwFreeSocketObjHold (DEFAULT_FREE_SOCKETOBJ_HOLD)
  210. , m_dwFreeBufferObjHold (DEFAULT_FREE_BUFFEROBJ_HOLD)
  211. , m_dwKeepAliveTime (DEFALUT_TCP_KEEPALIVE_TIME)
  212. , m_dwKeepAliveInterval (DEFALUT_TCP_KEEPALIVE_INTERVAL)
  213. , m_bReuseAddress (FALSE)
  214. , m_bMarkSilence (TRUE)
  215. {
  216. ASSERT(m_wsSocket.IsValid());
  217. ASSERT(m_pListener);
  218. ::ZeroMemory((void*)&m_soAddrIN, sizeof(SOCKADDR_IN));
  219. }
  220. virtual ~CTcpAgent()
  221. {
  222. Stop();
  223. }
  224. private:
  225. EnSendPolicy m_enSendPolicy;
  226. DWORD m_dwMaxConnectionCount;
  227. DWORD m_dwWorkerThreadCount;
  228. DWORD m_dwSocketBufferSize;
  229. DWORD m_dwFreeSocketObjLockTime;
  230. DWORD m_dwFreeSocketObjPool;
  231. DWORD m_dwFreeBufferObjPool;
  232. DWORD m_dwFreeSocketObjHold;
  233. DWORD m_dwFreeBufferObjHold;
  234. DWORD m_dwKeepAliveTime;
  235. DWORD m_dwKeepAliveInterval;
  236. BOOL m_bReuseAddress;
  237. BOOL m_bMarkSilence;
  238. private:
  239. CInitSocket m_wsSocket;
  240. LPFN_CONNECTEX m_pfnConnectEx;
  241. LPFN_DISCONNECTEX m_pfnDisconnectEx;
  242. private:
  243. ITcpAgentListener* m_pListener;
  244. BOOL m_bAsyncConnect;
  245. HANDLE m_hCompletePort;
  246. EnServiceState m_enState;
  247. EnSocketError m_enLastError;
  248. SOCKADDR_IN m_soAddrIN;
  249. vector<HANDLE> m_vtWorkerThreads;
  250. CPrivateHeap m_phSocket;
  251. CBufferObjPool m_bfObjPool;
  252. CSpinGuard m_csState;
  253. TSocketObjPtrPool m_bfActiveSockets;
  254. TSocketObjPtrList m_lsFreeSocket;
  255. TSocketObjPtrQueue m_lsGCSocket;
  256. };