AsyncSocketEx.h 12 KB

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