AsyncSocketEx.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /*CAsyncSocketEx by Tim Kosse ([email protected])
  2. Version 1.3 (2003-04-26)
  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 [email protected]
  53. */
  54. //---------------------------------------------------------------------------
  55. #ifndef AsyncSocketExH
  56. #define AsyncSocketExH
  57. //---------------------------------------------------------------------------
  58. #define FD_FORCEREAD (1<<15)
  59. //---------------------------------------------------------------------------
  60. #include <winsock2.h>
  61. #include <Ws2tcpip.h>
  62. //---------------------------------------------------------------------------
  63. class CAsyncSocketExHelperWindow;
  64. class CAsyncSocketExLayer;
  65. class CCriticalSectionWrapper;
  66. //---------------------------------------------------------------------------
  67. struct t_callbackMsg
  68. {
  69. CAsyncSocketExLayer* pLayer;
  70. int nType;
  71. int nParam1;
  72. int nParam2;
  73. char* str;
  74. };
  75. //---------------------------------------------------------------------------
  76. class CAsyncSocketEx
  77. {
  78. public:
  79. CAsyncSocketEx();
  80. virtual ~CAsyncSocketEx();
  81. BOOL Create(UINT nSocketPort = 0, int nSocketType = SOCK_STREAM,
  82. long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE,
  83. LPCTSTR lpszSocketAddress = NULL, int nFamily = AF_INET);
  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 | FD_CONNECT | FD_CLOSE);
  87. // Detaches a socket handle from a CAsyncSocketEx object.
  88. SOCKET Detach( );
  89. // Gets the error status for the last operation that failed.
  90. static int GetLastError();
  91. // Gets the address of the peer socket to which the socket is connected.
  92. BOOL GetPeerName(CString& rPeerAddress, UINT& rPeerPort);
  93. BOOL GetPeerName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
  94. // Gets the local name for a socket.
  95. BOOL GetSockName(CString& rSocketAddress, UINT& rSocketPort);
  96. BOOL GetSockName(SOCKADDR* lpSockAddr, int* lpSockAddrLen);
  97. // Retrieves a socket option.
  98. BOOL GetSockOpt(int nOptionName, void* lpOptionValue, int* lpOptionLen, int nLevel = SOL_SOCKET);
  99. // Sets a socket option.
  100. BOOL SetSockOpt(int nOptionName, const void* lpOptionValue, int nOptionLen, int nLevel = SOL_SOCKET);
  101. // Gets the socket family
  102. int GetFamily() const;
  103. // Sets the socket family
  104. bool SetFamily(int nFamily);
  105. // Operations
  106. // Accepts a connection on the socket.
  107. virtual BOOL Accept(CAsyncSocketEx& rConnectedSocket, SOCKADDR * lpSockAddr = NULL, int * lpSockAddrLen = NULL);
  108. // Requests event notification for the socket.
  109. BOOL AsyncSelect(long lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE);
  110. // Associates a local address with the socket.
  111. virtual BOOL Bind(UINT nSocketPort, LPCTSTR lpszSocketAddress);
  112. BOOL BindToAddr(const SOCKADDR* lpSockAddr, int nSockAddrLen);
  113. // Closes the socket.
  114. virtual void Close();
  115. // Establishes a connection to a peer socket.
  116. virtual BOOL Connect(LPCTSTR lpszHostAddress, UINT nHostPort);
  117. virtual BOOL Connect(const SOCKADDR * lpSockAddr, int nSockAddrLen);
  118. // Controls the mode of the socket.
  119. BOOL IOCtl(long lCommand, DWORD * lpArgument);
  120. // Establishes a socket to listen for incoming connection requests.
  121. BOOL Listen(int nConnectionBacklog = 5);
  122. // Receives data from the socket.
  123. virtual int Receive(void * lpBuf, int nBufLen, int nFlags = 0);
  124. // Sends data to a connected socket.
  125. virtual int Send(const void * lpBuf, int nBufLen, int nFlags = 0);
  126. // Disables Send and/or Receive calls on the socket.
  127. BOOL ShutDown(int nHow = sends);
  128. enum { receives = 0, sends = 1, both = 2 };
  129. // Overridable Notification Functions
  130. //----------------------------------
  131. // Notifies a listening socket that it can accept pending connection requests by calling Accept.
  132. virtual void OnAccept(int nErrorCode);
  133. // Notifies a socket that the socket connected to it has closed.
  134. virtual void OnClose(int nErrorCode);
  135. // Notifies a connecting socket that the connection attempt is complete, whether successfully or in error.
  136. virtual void OnConnect(int nErrorCode);
  137. // Notifies a listening socket that there is data to be retrieved by calling Receive.
  138. virtual void OnReceive(int nErrorCode);
  139. // Notifies a socket that it can send data by calling Send.
  140. virtual void OnSend(int nErrorCode);
  141. // Additional functions
  142. // Resets layer chain.
  143. void RemoveAllLayers();
  144. // Attaches a new layer to the socket.
  145. BOOL AddLayer(CAsyncSocketExLayer * pLayer);
  146. // Is a layer attached to the socket?
  147. BOOL IsLayerAttached() const;
  148. // Returns the handle of the socket.
  149. SOCKET GetSocketHandle();
  150. // Trigers an event on the socket
  151. // Any combination of FD_READ, FD_WRITE, FD_CLOSE, FD_ACCEPT, FD_CONNECT and FD_FORCEREAD is valid for lEvent.
  152. BOOL TriggerEvent(long lEvent);
  153. protected:
  154. // Strucure to hold the socket data
  155. struct t_AsyncSocketExData
  156. {
  157. SOCKET hSocket; // Socket handle
  158. int nSocketIndex; // Index of socket, required by CAsyncSocketExHelperWindow
  159. int nFamily;
  160. addrinfo * addrInfo, * nextAddr; // Iterate through protocols on connect failure
  161. bool onCloseCalled; // Set to true on first received OnClose event
  162. } m_SocketData;
  163. // If using layers, only the events specified with m_lEvent will send to the event handlers.
  164. long m_lEvent;
  165. // AsyncGetHostByName
  166. char *m_pAsyncGetHostByNameBuffer; // Buffer for hostend structure
  167. HANDLE m_hAsyncGetHostByNameHandle; // TaskHandle
  168. int m_nAsyncGetHostByNamePort; // Port to connect to
  169. // Returns the handle of the helper window
  170. HWND GetHelperWindowHandle();
  171. // Attaches socket handle to helper window
  172. void AttachHandle(SOCKET hSocket);
  173. // Detaches socket handle to helper window
  174. void DetachHandle(SOCKET hSocket);
  175. // Critical section for thread synchronization
  176. static CCriticalSectionWrapper m_sGlobalCriticalSection;
  177. // Pointer to the data of the local thread
  178. struct t_AsyncSocketExThreadData
  179. {
  180. CAsyncSocketExHelperWindow * m_pHelperWindow;
  181. int nInstanceCount;
  182. DWORD nThreadId;
  183. std::list<CAsyncSocketEx *> layerCloseNotify;
  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. // Iterate through protocols on failure
  196. bool TryNextProtocol();
  197. void ResendCloseNotify();
  198. // Add a new notification to the list of pending callbacks
  199. void AddCallbackNotification(const t_callbackMsg & msg);
  200. int m_nPendingEvents;
  201. int GetState() const;
  202. virtual void SetState(int nState);
  203. static const TCHAR * GetStateDesc(int nState);
  204. static bool LogStateChange(int nState1, int nState2);
  205. int m_nState;
  206. // Layer chain
  207. CAsyncSocketExLayer * m_pFirstLayer;
  208. CAsyncSocketExLayer * m_pLastLayer;
  209. friend CAsyncSocketExLayer;
  210. // Called by the layers to notify application of some events
  211. virtual int OnLayerCallback(std::list<t_callbackMsg> & callbacks);
  212. // Used by Bind with AF_UNSPEC sockets
  213. UINT m_nSocketPort;
  214. LPTSTR m_lpszSocketAddress;
  215. friend CAsyncSocketExHelperWindow;
  216. // Pending callbacks
  217. std::list<t_callbackMsg> m_pendingCallbacks;
  218. virtual void LogSocketMessageRaw(int nMessageType, LPCTSTR pMsg) {};
  219. virtual bool LoggingSocketMessage(int nMessageType) { return true; };
  220. virtual int GetSocketOptionVal(int OptionID) const { DebugFail(); return 0; };
  221. virtual void ConfigureSocket() {};
  222. };
  223. //---------------------------------------------------------------------------
  224. #define LAYERCALLBACK_STATECHANGE 0
  225. #define LAYERCALLBACK_LAYERSPECIFIC 1
  226. //---------------------------------------------------------------------------
  227. enum SocketState
  228. {
  229. notsock,
  230. unconnected,
  231. connecting,
  232. listening,
  233. connected,
  234. closed,
  235. aborted,
  236. attached
  237. };
  238. //---------------------------------------------------------------------------
  239. inline TCHAR* Inet6AddrToString(in6_addr & addr)
  240. {
  241. LPTSTR buf = new TCHAR[512];
  242. _sntprintf(buf, 512, L"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  243. addr.s6_bytes[0], addr.s6_bytes[1], addr.s6_bytes[2], addr.s6_bytes[3],
  244. addr.s6_bytes[4], addr.s6_bytes[5], addr.s6_bytes[6], addr.s6_bytes[7],
  245. addr.s6_bytes[8], addr.s6_bytes[9], addr.s6_bytes[10], addr.s6_bytes[11],
  246. addr.s6_bytes[12], addr.s6_bytes[13], addr.s6_bytes[14], addr.s6_bytes[15]);
  247. return buf;
  248. }
  249. //---------------------------------------------------------------------------
  250. class CCriticalSectionWrapper
  251. {
  252. public:
  253. CCriticalSectionWrapper()
  254. {
  255. m_bInitialized = TRUE;
  256. InitializeCriticalSection(&m_criticalSection);
  257. }
  258. ~CCriticalSectionWrapper()
  259. {
  260. if (m_bInitialized)
  261. DeleteCriticalSection(&m_criticalSection);
  262. m_bInitialized = FALSE;
  263. }
  264. void Lock()
  265. {
  266. if (m_bInitialized)
  267. EnterCriticalSection(&m_criticalSection);
  268. }
  269. void Unlock()
  270. {
  271. if (m_bInitialized)
  272. LeaveCriticalSection(&m_criticalSection);
  273. }
  274. protected:
  275. CRITICAL_SECTION m_criticalSection;
  276. BOOL m_bInitialized;
  277. };
  278. //---------------------------------------------------------------------------
  279. #endif // AsyncSocketExH