PageRenderTime 69ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/3rdParty/include/nio/AsyncSocketExLayer.cpp

https://gitlab.com/yoage/TTWinClient
C++ | 604 lines | 473 code | 65 blank | 66 comment | 89 complexity | 6b972dd8fed60d7b96f96bd542c060b8 MD5 | raw file
Possible License(s): LGPL-3.0
  1. /*CAsyncSocketEx by Tim Kosse (Tim.Kosse@gmx.de)
  2. Version 1.1 (2002-11-01)
  3. --------------------------------------------------------
  4. Introduction:
  5. -------------
  6. CAsyncSocketEx is a replacement for the MFC class CAsyncSocket.
  7. This class was written because CAsyncSocket is not the fastest WinSock
  8. wrapper and it's very hard to add new functionality to CAsyncSocket
  9. derived classes. This class offers the same functionality as CAsyncSocket.
  10. Also, CAsyncSocketEx offers some enhancements which were not possible with
  11. CAsyncSocket without some tricks.
  12. How do I use it?
  13. ----------------
  14. Basically exactly like CAsyncSocket.
  15. To use CAsyncSocketEx, just replace all occurrences of CAsyncSocket in your
  16. code with CAsyncSocketEx, if you did not enhance CAsyncSocket yourself in
  17. any way, you won't have to change anything else in your code.
  18. Why is CAsyncSocketEx faster?
  19. -----------------------------
  20. CAsyncSocketEx is slightly faster when dispatching notification event messages.
  21. First have a look at the way CAsyncSocket works. For each thread that uses
  22. CAsyncSocket, a window is created. CAsyncSocket calls WSAAsyncSelect with
  23. the handle of that window. Until here, CAsyncSocketEx works the same way.
  24. But CAsyncSocket uses only one window message (WM_SOCKET_NOTIFY) for all
  25. sockets within one thread. When the window recieve WM_SOCKET_NOTIFY, wParam
  26. contains the socket handle and the window looks up an CAsyncSocket instance
  27. using a map. CAsyncSocketEx works differently. It's helper window uses a
  28. wide range of different window messages (WM_USER through 0xBFFF) and passes
  29. a different message to WSAAsyncSelect for each socket. When a message in
  30. the specified range is received, CAsyncSocketEx looks up the pointer to a
  31. CAsyncSocketEx instance in an Array using the index of message - WM_USER.
  32. As you can see, CAsyncSocketEx uses the helper window in a more efficient
  33. way, as it don't have to use the slow maps to lookup it's own instance.
  34. Still, speed increase is not very much, but it may be noticeable when using
  35. a lot of sockets at the same time.
  36. Please note that the changes do not affect the raw data throughput rate,
  37. CAsyncSocketEx only dispatches the notification messages faster.
  38. What else does CAsyncSocketEx offer?
  39. ------------------------------------
  40. CAsyncSocketEx offers a flexible layer system. One example is the proxy layer.
  41. Just create an instance of the proxy layer, configure it and add it to the layer
  42. chain of your CAsyncSocketEx instance. After that, you can connect through
  43. proxies.
  44. Benefit: You don't have to change much to use the layer system.
  45. Another layer that is currently in development is the SSL layer to establish
  46. SSL encrypted connections.
  47. License
  48. -------
  49. Feel free to use this class, as long as you don't claim that you wrote it
  50. and this copyright notice stays intact in the source files.
  51. If you use this class in commercial applications, please send a short message
  52. to tim.kosse@gmx.de
  53. */#include "stdafx.h"
  54. #include "AsyncSocketExLayer.h"
  55. #include "AsyncSocketEx.h"
  56. #ifdef _DEBUG
  57. #undef THIS_FILE
  58. static char THIS_FILE[]=__FILE__;
  59. #define new DEBUG_NEW
  60. #endif
  61. #define WM_SOCKETEX_NOTIFY (WM_USER+2)
  62. //////////////////////////////////////////////////////////////////////
  63. // Konstruktion/Destruktion
  64. //////////////////////////////////////////////////////////////////////
  65. CAsyncSocketExLayer::CAsyncSocketExLayer()
  66. {
  67. m_pOwnerSocket=0;
  68. m_pNextLayer=0;
  69. m_nLayerState=notsock;
  70. m_nCriticalError=0;
  71. }
  72. CAsyncSocketExLayer::~CAsyncSocketExLayer()
  73. {
  74. }
  75. CAsyncSocketExLayer *CAsyncSocketExLayer::AddLayer(CAsyncSocketExLayer *pLayer, CAsyncSocketEx *pOwnerSocket)
  76. {
  77. ASSERT(pLayer);
  78. ASSERT(pOwnerSocket);
  79. if (m_pNextLayer)
  80. {
  81. return m_pNextLayer->AddLayer(pLayer, pOwnerSocket);
  82. }
  83. else
  84. {
  85. ASSERT(m_pOwnerSocket==pOwnerSocket);
  86. pLayer->Init(this, m_pOwnerSocket);
  87. m_pNextLayer=pLayer;
  88. }
  89. return m_pNextLayer;
  90. }
  91. int CAsyncSocketExLayer::Receive(void* lpBuf, int nBufLen, int nFlags /*=0*/)
  92. {
  93. return ReceiveNext(lpBuf, nBufLen, nFlags);
  94. }
  95. int CAsyncSocketExLayer::Send(const void* lpBuf, int nBufLen, int nFlags /*=0*/)
  96. {
  97. return SendNext(lpBuf, nBufLen, nFlags);
  98. }
  99. void CAsyncSocketExLayer::OnReceive(int nErrorCode)
  100. {
  101. if (m_pPrevLayer)
  102. m_pPrevLayer->OnReceive(nErrorCode);
  103. else
  104. if (m_pOwnerSocket->m_lEvent&FD_READ)
  105. m_pOwnerSocket->onReceive(nErrorCode);
  106. }
  107. void CAsyncSocketExLayer::OnSend(int nErrorCode)
  108. {
  109. if (m_pPrevLayer)
  110. m_pPrevLayer->OnSend(nErrorCode);
  111. else
  112. if (m_pOwnerSocket->m_lEvent&FD_WRITE)
  113. m_pOwnerSocket->onSend(nErrorCode);
  114. }
  115. void CAsyncSocketExLayer::OnConnect(int nErrorCode)
  116. {
  117. if (m_pPrevLayer)
  118. m_pPrevLayer->OnConnect(nErrorCode);
  119. else
  120. if (m_pOwnerSocket->m_lEvent&FD_CONNECT)
  121. m_pOwnerSocket->onConnect(nErrorCode);
  122. }
  123. void CAsyncSocketExLayer::OnAccept(int nErrorCode)
  124. {
  125. if (m_pPrevLayer)
  126. m_pPrevLayer->OnAccept(nErrorCode);
  127. else
  128. if (m_pOwnerSocket->m_lEvent&FD_ACCEPT)
  129. m_pOwnerSocket->onAccept(nErrorCode);
  130. }
  131. void CAsyncSocketExLayer::OnClose(int nErrorCode)
  132. {
  133. if (m_pPrevLayer)
  134. m_pPrevLayer->OnClose(nErrorCode);
  135. else
  136. if (m_pOwnerSocket->m_lEvent&FD_CLOSE)
  137. m_pOwnerSocket->onClose(nErrorCode);
  138. }
  139. BOOL CAsyncSocketExLayer::TriggerEvent(long lEvent, int nErrorCode, BOOL bPassThrough /*=FALSE*/ )
  140. {
  141. ASSERT(m_pOwnerSocket);
  142. if (m_pOwnerSocket->m_SocketData.hSocket==INVALID_SOCKET)
  143. return FALSE;
  144. if ( lEvent&FD_CONNECT)
  145. {
  146. ASSERT(bPassThrough);
  147. if (!nErrorCode)
  148. ASSERT(bPassThrough && GetLayerState()==connected);
  149. else if (nErrorCode)
  150. {
  151. SetLayerState(aborted);
  152. m_nCriticalError=nErrorCode;
  153. }
  154. }
  155. else if ( lEvent&FD_CLOSE && !nErrorCode)
  156. {
  157. SetLayerState(closed);
  158. }
  159. else if ( lEvent&FD_CLOSE && nErrorCode)
  160. {
  161. SetLayerState(aborted);
  162. m_nCriticalError=nErrorCode;
  163. }
  164. ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData);
  165. ASSERT(m_pOwnerSocket->m_pLocalAsyncSocketExThreadData->m_pHelperWindow);
  166. ASSERT(m_pOwnerSocket->m_SocketData.nSocketIndex!=-1);
  167. t_LayerNotifyMsg *pMsg=new t_LayerNotifyMsg;
  168. pMsg->lEvent = ( lEvent % 0xffff ) + ( nErrorCode << 16);
  169. pMsg->pLayer=bPassThrough?m_pPrevLayer:this;
  170. BOOL res=PostMessage(m_pOwnerSocket->GetHelperWindowHandle(), WM_USER, (WPARAM)m_pOwnerSocket, (LPARAM)pMsg);
  171. if (!res)
  172. delete pMsg;
  173. return res;
  174. }
  175. void CAsyncSocketExLayer::Close()
  176. {
  177. CloseNext();
  178. }
  179. void CAsyncSocketExLayer::CloseNext()
  180. {
  181. SetLayerState(notsock);
  182. if (m_pNextLayer)
  183. m_pNextLayer->Close();
  184. }
  185. BOOL CAsyncSocketExLayer::Connect(LPCTSTR lpszHostAddress, UINT nHostPort)
  186. {
  187. return ConnectNext(lpszHostAddress, nHostPort);
  188. }
  189. BOOL CAsyncSocketExLayer::Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  190. {
  191. return ConnectNext(lpSockAddr, nSockAddrLen);
  192. }
  193. int CAsyncSocketExLayer::SendNext(const void *lpBuf, int nBufLen, int nFlags /*=0*/)
  194. {
  195. if (m_nCriticalError)
  196. {
  197. WSASetLastError(m_nCriticalError);
  198. return SOCKET_ERROR;
  199. }
  200. else if (GetLayerState()==notsock)
  201. {
  202. WSASetLastError(WSAENOTSOCK);
  203. return SOCKET_ERROR;
  204. }
  205. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  206. {
  207. WSASetLastError(WSAENOTCONN);
  208. return SOCKET_ERROR;
  209. }
  210. if (!m_pNextLayer)
  211. {
  212. ASSERT(m_pOwnerSocket);
  213. return send(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  214. }
  215. else
  216. return m_pNextLayer->Send(lpBuf, nBufLen, nFlags);
  217. }
  218. int CAsyncSocketExLayer::ReceiveNext(void *lpBuf, int nBufLen, int nFlags /*=0*/)
  219. {
  220. if (m_nCriticalError)
  221. {
  222. WSASetLastError(m_nCriticalError);
  223. return SOCKET_ERROR;
  224. }
  225. else if (GetLayerState()==notsock)
  226. {
  227. WSASetLastError(WSAENOTSOCK);
  228. return SOCKET_ERROR;
  229. }
  230. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  231. {
  232. WSASetLastError(WSAENOTCONN);
  233. return SOCKET_ERROR;
  234. }
  235. if (!m_pNextLayer)
  236. {
  237. ASSERT(m_pOwnerSocket);
  238. return recv(m_pOwnerSocket->GetSocketHandle(), (LPSTR)lpBuf, nBufLen, nFlags);
  239. }
  240. else
  241. return m_pNextLayer->Receive(lpBuf, nBufLen, nFlags);
  242. }
  243. BOOL CAsyncSocketExLayer::ConnectNext(LPCTSTR lpszHostAddress, UINT nHostPort)
  244. {
  245. ASSERT(GetLayerState()==unconnected);
  246. ASSERT(m_pOwnerSocket);
  247. BOOL res;
  248. if (m_pNextLayer)
  249. res = m_pNextLayer->Connect(lpszHostAddress, nHostPort);
  250. else
  251. {
  252. USES_CONVERSION;
  253. ASSERT(lpszHostAddress != NULL);
  254. SOCKADDR_IN sockAddr;
  255. memset(&sockAddr,0,sizeof(sockAddr));
  256. LPSTR lpszAscii = T2A((LPTSTR)lpszHostAddress);
  257. sockAddr.sin_family = AF_INET;
  258. sockAddr.sin_addr.s_addr = inet_addr(lpszAscii);
  259. if (sockAddr.sin_addr.s_addr == INADDR_NONE)
  260. {
  261. LPHOSTENT lphost;
  262. lphost = gethostbyname(lpszAscii);
  263. if (lphost != NULL)
  264. sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
  265. else
  266. {
  267. WSASetLastError(WSAEINVAL);
  268. res = FALSE;
  269. }
  270. }
  271. sockAddr.sin_port = htons((u_short)nHostPort);
  272. res = ( SOCKET_ERROR!=connect(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, sizeof(sockAddr)) );
  273. }
  274. if (res || WSAGetLastError()==WSAEWOULDBLOCK)
  275. {
  276. SetLayerState(connecting);
  277. }
  278. return res;
  279. }
  280. BOOL CAsyncSocketExLayer::ConnectNext( const SOCKADDR* lpSockAddr, int nSockAddrLen )
  281. {
  282. ASSERT(GetLayerState()==unconnected);
  283. ASSERT(m_pOwnerSocket);
  284. BOOL res;
  285. if (m_pNextLayer)
  286. res=m_pNextLayer->Connect(lpSockAddr, nSockAddrLen);
  287. else
  288. res = (SOCKET_ERROR!=connect(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, nSockAddrLen));
  289. if (res || WSAGetLastError()==WSAEWOULDBLOCK)
  290. SetLayerState(connecting);
  291. return res;
  292. }
  293. //Gets the address of the peer socket to which the socket is connected
  294. #ifdef _AFX
  295. BOOL CAsyncSocketExLayer::GetPeerName( CString& rPeerAddress, UINT& rPeerPort )
  296. {
  297. return GetPeerNameNext(rPeerAddress, rPeerPort);
  298. }
  299. BOOL CAsyncSocketExLayer::GetPeerNameNext( CString& rPeerAddress, UINT& rPeerPort )
  300. {
  301. if (m_pNextLayer)
  302. return m_pNextLayer->GetPeerName(rPeerAddress, rPeerPort);
  303. else
  304. {
  305. ASSERT(m_pOwnerSocket);
  306. SOCKADDR_IN sockAddr;
  307. memset(&sockAddr, 0, sizeof(sockAddr));
  308. int nSockAddrLen = sizeof(sockAddr);
  309. if (!getpeername(m_pOwnerSocket->GetSocketHandle(), (SOCKADDR*)&sockAddr, &nSockAddrLen))
  310. {
  311. rPeerPort = ntohs(sockAddr.sin_port);
  312. rPeerAddress = inet_ntoa(sockAddr.sin_addr);
  313. return TRUE;
  314. }
  315. else
  316. return FALSE;
  317. }
  318. }
  319. #endif //_AFX
  320. BOOL CAsyncSocketExLayer::GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  321. {
  322. return GetPeerNameNext(lpSockAddr, lpSockAddrLen);
  323. }
  324. BOOL CAsyncSocketExLayer::GetPeerNameNext( SOCKADDR* lpSockAddr, int* lpSockAddrLen )
  325. {
  326. if (m_pNextLayer)
  327. return m_pNextLayer->GetPeerName(lpSockAddr, lpSockAddrLen);
  328. else
  329. {
  330. ASSERT(m_pOwnerSocket);
  331. if ( !getpeername(m_pOwnerSocket->GetSocketHandle(), lpSockAddr, lpSockAddrLen) )
  332. return TRUE;
  333. else
  334. return FALSE;
  335. }
  336. }
  337. void CAsyncSocketExLayer::Init(CAsyncSocketExLayer *pPrevLayer, CAsyncSocketEx *pOwnerSocket)
  338. {
  339. ASSERT(pOwnerSocket);
  340. m_pPrevLayer=pPrevLayer;
  341. m_pOwnerSocket=pOwnerSocket;
  342. m_pNextLayer=0;
  343. }
  344. int CAsyncSocketExLayer::GetLayerState()
  345. {
  346. return m_nLayerState;
  347. }
  348. void CAsyncSocketExLayer::CallEvent(int nEvent, int nErrorCode)
  349. {
  350. if (m_nCriticalError)
  351. return;
  352. m_nCriticalError=nErrorCode;
  353. switch (nEvent)
  354. {
  355. case FD_READ:
  356. case FD_FORCEREAD:
  357. if (GetLayerState()==connected)
  358. {
  359. if (nErrorCode)
  360. SetLayerState(aborted);
  361. OnReceive(nErrorCode);
  362. }
  363. break;
  364. case FD_WRITE:
  365. if (GetLayerState()==connected)
  366. {
  367. if (nErrorCode)
  368. SetLayerState(aborted);
  369. OnSend(nErrorCode);
  370. }
  371. break;
  372. case FD_CONNECT:
  373. if (GetLayerState()==connecting)
  374. {
  375. if (!nErrorCode)
  376. SetLayerState(connected);
  377. else
  378. SetLayerState(aborted);
  379. OnConnect(nErrorCode);
  380. }
  381. break;
  382. case FD_ACCEPT:
  383. if (GetLayerState()==listening)
  384. {
  385. if (!nErrorCode)
  386. SetLayerState(connected);
  387. else
  388. SetLayerState(aborted);
  389. OnAccept(nErrorCode);
  390. }
  391. break;
  392. case FD_CLOSE:
  393. if (GetLayerState()==connected)
  394. {
  395. if (nErrorCode)
  396. SetLayerState(aborted);
  397. else
  398. SetLayerState(closed);
  399. OnClose(nErrorCode);
  400. }
  401. break;
  402. }
  403. }
  404. //Creates a socket
  405. BOOL CAsyncSocketExLayer::Create(UINT nSocketPort, int nSocketType,
  406. long lEvent, LPCTSTR lpszSocketAddress)
  407. {
  408. return CreateNext(nSocketPort, nSocketType, lEvent, lpszSocketAddress);
  409. }
  410. BOOL CAsyncSocketExLayer::CreateNext(UINT nSocketPort, int nSocketType, long lEvent, LPCTSTR lpszSocketAddress)
  411. {
  412. ASSERT(GetLayerState()==notsock);
  413. BOOL res=FALSE;
  414. if (m_pNextLayer)
  415. res=m_pNextLayer->Create(nSocketPort, nSocketType, lEvent, lpszSocketAddress);
  416. else
  417. {
  418. SOCKET hSocket=socket(AF_INET, nSocketType, 0);
  419. if (hSocket==INVALID_SOCKET)
  420. res=FALSE;
  421. m_pOwnerSocket->m_SocketData.hSocket=hSocket;
  422. m_pOwnerSocket->AttachHandle(hSocket);
  423. if (!m_pOwnerSocket->AsyncSelect(lEvent))
  424. {
  425. m_pOwnerSocket->Close();
  426. res=FALSE;
  427. }
  428. if (m_pOwnerSocket->m_pFirstLayer)
  429. {
  430. if (WSAAsyncSelect(m_pOwnerSocket->m_SocketData.hSocket, m_pOwnerSocket->GetHelperWindowHandle(), m_pOwnerSocket->m_SocketData.nSocketIndex+WM_SOCKETEX_NOTIFY, FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE) )
  431. {
  432. m_pOwnerSocket->Close();
  433. res=FALSE;
  434. }
  435. }
  436. if (!m_pOwnerSocket->Bind(nSocketPort, lpszSocketAddress))
  437. {
  438. m_pOwnerSocket->Close();
  439. res=FALSE;
  440. }
  441. res=TRUE;
  442. }
  443. if (res)
  444. SetLayerState(unconnected);
  445. return res;
  446. }
  447. void CAsyncSocketExLayer::SetLayerState(int nLayerState)
  448. {
  449. ASSERT(m_pOwnerSocket);
  450. int nOldLayerState=GetLayerState();
  451. m_nLayerState=nLayerState;
  452. if (nOldLayerState!=nLayerState)
  453. DoLayerCallback(LAYERCALLBACK_STATECHANGE, GetLayerState(), nOldLayerState);
  454. }
  455. int CAsyncSocketExLayer::DoLayerCallback(int nType, int nParam1, int nParam2)
  456. {
  457. ASSERT(m_pOwnerSocket);
  458. int nError=WSAGetLastError();
  459. int res = m_pOwnerSocket->OnLayerCallback(this, nType, nParam1, nParam2);
  460. WSASetLastError(nError);
  461. return res;
  462. }
  463. BOOL CAsyncSocketExLayer::Listen( int nConnectionBacklog)
  464. {
  465. return ListenNext( nConnectionBacklog);
  466. }
  467. BOOL CAsyncSocketExLayer::ListenNext( int nConnectionBacklog)
  468. {
  469. ASSERT(GetLayerState()==unconnected);
  470. BOOL res;
  471. if (m_pNextLayer)
  472. res=m_pNextLayer->Listen(nConnectionBacklog);
  473. else
  474. res=listen(m_pOwnerSocket->GetSocketHandle(), nConnectionBacklog);
  475. if (res)
  476. {
  477. SetLayerState(listening);
  478. }
  479. return res;
  480. }
  481. BOOL CAsyncSocketExLayer::Accept( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  482. {
  483. return AcceptNext(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  484. }
  485. BOOL CAsyncSocketExLayer::AcceptNext( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr /*=NULL*/, int* lpSockAddrLen /*=NULL*/ )
  486. {
  487. ASSERT(GetLayerState()==listening);
  488. BOOL res;
  489. if (m_pNextLayer)
  490. res=m_pNextLayer->Accept(rConnectedSocket, lpSockAddr, lpSockAddrLen);
  491. else
  492. {
  493. SOCKET hTemp = accept(m_pOwnerSocket->m_SocketData.hSocket, lpSockAddr, lpSockAddrLen);
  494. if (hTemp == INVALID_SOCKET)
  495. return FALSE;
  496. VERIFY(rConnectedSocket.InitAsyncSocketExInstance());
  497. rConnectedSocket.m_SocketData.hSocket=hTemp;
  498. rConnectedSocket.AttachHandle(hTemp);
  499. }
  500. return TRUE;
  501. }
  502. BOOL CAsyncSocketExLayer::ShutDown(int nHow /*=sends*/)
  503. {
  504. return ShutDownNext(nHow);
  505. }
  506. BOOL CAsyncSocketExLayer::ShutDownNext(int nHow /*=sends*/)
  507. {
  508. if (m_nCriticalError)
  509. {
  510. WSASetLastError(m_nCriticalError);
  511. return FALSE;
  512. }
  513. else if (GetLayerState()==notsock)
  514. {
  515. WSASetLastError(WSAENOTSOCK);
  516. return FALSE;
  517. }
  518. else if (GetLayerState()==unconnected || GetLayerState()==connecting || GetLayerState()==listening)
  519. {
  520. WSASetLastError(WSAENOTCONN);
  521. return FALSE;
  522. }
  523. if (!m_pNextLayer)
  524. {
  525. ASSERT(m_pOwnerSocket);
  526. return shutdown(m_pOwnerSocket->GetSocketHandle(), nHow);
  527. }
  528. else
  529. return m_pNextLayer->ShutDownNext(nHow);
  530. }