PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/3rdParty/include/nio/AsyncSocketEx.h

https://gitlab.com/yoage/TTWinClient
C Header | 276 lines | 100 code | 58 blank | 118 comment | 0 complexity | a768a7495e2b0d222c6b84137bc2cf5c MD5 | raw file
Possible License(s): LGPL-3.0
  1. /*CAsyncSocketEx by Tim Kosse (Tim.Kosse@gmx.de)
  2. Version 1.2 (2003-03-28)
  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. */
  54. #if !defined(AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_)
  55. #define AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_
  56. #if _MSC_VER > 1000
  57. #pragma once
  58. #endif // _MSC_VER > 1000
  59. #define FD_FORCEREAD (1<<15)
  60. #include "winsock.h"
  61. #include "TTLogic/TTLogicDll.h"
  62. class CAsyncSocketExHelperWindow;
  63. #ifndef NOLAYERS
  64. class CAsyncSocketExLayer;
  65. #endif //NOLAYERS
  66. class CCriticalSectionWrapper;
  67. class TTLOGIC_CLASS CAsyncSocketEx
  68. {
  69. public:
  70. ///////////////////////////////////////
  71. //Functions that imitate CAsyncSocket//
  72. ///////////////////////////////////////
  73. //Construction
  74. //------------
  75. //Constructs a CAsyncSocketEx object.
  76. CAsyncSocketEx();
  77. virtual ~CAsyncSocketEx();
  78. //Creates a socket.
  79. BOOL Create(UINT nSocketPort = 0, int nSocketType = SOCK_STREAM,
  80. long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
  81. LPCTSTR lpszSocketAddress = NULL );
  82. //Attributes
  83. //---------
  84. //Attaches a socket handle to a CAsyncSocketEx object.
  85. BOOL Attach( SOCKET hSocket,
  86. long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT |
  87. FD_CONNECT | FD_CLOSE );
  88. //Detaches a socket handle from a CAsyncSocketEx object.
  89. SOCKET Detach( );
  90. //Gets the error status for the last operation that failed.
  91. static int GetLastError();
  92. //Gets the address of the peer socket to which the socket is connected.
  93. #ifdef _AFX
  94. BOOL GetPeerName( CString& rPeerAddress, UINT& rPeerPort );
  95. #endif
  96. BOOL GetPeerName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );
  97. //Gets the local name for a socket.
  98. #ifdef _AFX
  99. BOOL GetSockName( CString& rSocketAddress, UINT& rSocketPort );
  100. #endif
  101. BOOL GetSockName( SOCKADDR* lpSockAddr, int* lpSockAddrLen );
  102. //Retrieves a socket option.
  103. BOOL GetSockOpt(int nOptionName, void* lpOptionValue, int* lpOptionLen, int nLevel = SOL_SOCKET);
  104. //Sets a socket option.
  105. BOOL SetSockOpt(int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET);
  106. //Operations
  107. //----------
  108. //Accepts a connection on the socket.
  109. virtual BOOL Accept( CAsyncSocketEx& rConnectedSocket, SOCKADDR* lpSockAddr = NULL, int* lpSockAddrLen = NULL );
  110. //Requests event notification for the socket.
  111. BOOL AsyncSelect( long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE );
  112. //Associates a local address with the socket.
  113. BOOL Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress);
  114. BOOL Bind(const SOCKADDR* lpSockAddr, int nSockAddrLen);
  115. //Closes the socket.
  116. virtual void Close();
  117. //Establishes a connection to a peer socket.
  118. virtual BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort);
  119. virtual BOOL Connect( const SOCKADDR* lpSockAddr, int nSockAddrLen );
  120. //Controls the mode of the socket.
  121. BOOL IOCtl( long lCommand, DWORD* lpArgument );
  122. //Establishes a socket to listen for incoming connection requests.
  123. BOOL Listen( int nConnectionBacklog = 5 );
  124. //Receives data from the socket.
  125. virtual int Receive(void* lpBuf, int nBufLen, int nFlags = 0);
  126. //Sends data to a connected socket.
  127. virtual int Send(const void* lpBuf, int nBufLen, int nFlags = 0);
  128. //Disables Send and/or Receive calls on the socket.
  129. BOOL ShutDown( int nHow = sends );
  130. enum { receives = 0, sends = 1, both = 2 };
  131. //Overridable Notification Functions
  132. //----------------------------------
  133. //Notifies a listening socket that it can accept pending connection requests by calling Accept.
  134. virtual void onAccept(int nErrorCode);
  135. //Notifies a socket that the socket connected to it has closed.
  136. virtual void onClose(int nErrorCode);
  137. //Notifies a connecting socket that the connection attempt is complete, whether successfully or in error.
  138. virtual void onConnect(int nErrorCode);
  139. //Notifies a listening socket that there is data to be retrieved by calling Receive.
  140. virtual void onReceive(int nErrorCode);
  141. //Notifies a socket that it can send data by calling Send.
  142. virtual void onSend(int nErrorCode);
  143. ////////////////////////
  144. //Additional functions//
  145. ////////////////////////
  146. #ifndef NOLAYERS
  147. //Resets layer chain.
  148. void RemoveAllLayers();
  149. //Attaches a new layer to the socket.
  150. BOOL AddLayer(CAsyncSocketExLayer *pLayer);
  151. #endif //NOLAYERS
  152. //Returns the handle of the socket.
  153. SOCKET GetSocketHandle();
  154. //Trigers an event on the socket
  155. // Any combination of FD_READ, FD_WRITE, FD_CLOSE, FD_ACCEPT, FD_CONNECT and FD_FORCEREAD is valid for lEvent.
  156. BOOL TriggerEvent(long lEvent);
  157. protected:
  158. //Strucure to hold the socket data
  159. struct t_AsyncSocketExData
  160. {
  161. SOCKET hSocket; //Socket handle
  162. int nSocketIndex; //Index of socket, required by CAsyncSocketExHelperWindow
  163. } m_SocketData;
  164. //If using layers, only the events specified with m_lEvent will send to the event handlers.
  165. long m_lEvent;
  166. //AsyncGetHostByName
  167. char *m_pAsyncGetHostByNameBuffer; //Buffer for hostend structure
  168. HANDLE m_hAsyncGetHostByNameHandle; //TaskHandle
  169. int m_nAsyncGetHostByNamePort; //Port to connect to
  170. //Returns the handle of the helper window
  171. HWND GetHelperWindowHandle();
  172. //Attaches socket handle to helper window
  173. void AttachHandle(SOCKET hSocket);
  174. //Detaches socket handle to helper window
  175. void DetachHandle(SOCKET hSocket);
  176. //Critical section for thread synchronization
  177. static CCriticalSectionWrapper m_sGlobalCriticalSection;
  178. //Pointer to the data of the local thread
  179. struct t_AsyncSocketExThreadData
  180. {
  181. CAsyncSocketExHelperWindow *m_pHelperWindow;
  182. int nInstanceCount;
  183. DWORD nThreadId;
  184. } *m_pLocalAsyncSocketExThreadData;
  185. //List of the data structures for all threads
  186. static struct t_AsyncSocketExThreadDataList
  187. {
  188. t_AsyncSocketExThreadDataList *pNext;
  189. t_AsyncSocketExThreadData *pThreadData;
  190. } *m_spAsyncSocketExThreadDataList;
  191. //Initializes Thread data and helper window, fills m_pLocalAsyncSocketExThreadData
  192. BOOL InitAsyncSocketExInstance();
  193. //Destroys helper window after last instance of CAsyncSocketEx in current thread has been closed
  194. void FreeAsyncSocketExInstance();
  195. #ifndef NOLAYERS
  196. //Layer chain
  197. CAsyncSocketExLayer *m_pFirstLayer;
  198. CAsyncSocketExLayer *m_pLastLayer;
  199. friend CAsyncSocketExLayer;
  200. //Called by the layers to notify application of some events
  201. virtual int OnLayerCallback(const CAsyncSocketExLayer *pLayer, int nType, int nParam1, int nParam2);
  202. #endif //NOLAYERS
  203. friend CAsyncSocketExHelperWindow;
  204. };
  205. #ifndef NOLAYERS
  206. #define LAYERCALLBACK_STATECHANGE 0
  207. #define LAYERCALLBACK_LAYERSPECIFIC 1
  208. #endif //NOLAYERS
  209. #endif // !defined(AFX_ASYNCSOCKETEX_H__AA9E4531_63B1_442F_9A71_09B2FEEDF34E__INCLUDED_)