TCPServer.hpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. Copyright (c) 2009 Christopher A. Taylor. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. * Redistributions of source code must retain the above copyright notice,
  6. this list of conditions and the following disclaimer.
  7. * Redistributions in binary form must reproduce the above copyright notice,
  8. this list of conditions and the following disclaimer in the documentation
  9. and/or other materials provided with the distribution.
  10. * Neither the name of LibCat nor the names of its contributors may be used
  11. to endorse or promote products derived from this software without
  12. specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  14. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  17. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  19. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  20. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  21. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  22. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  23. POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #ifndef CAT_THREAD_POOL_SOCKETS_HPP
  26. #define CAT_THREAD_POOL_SOCKETS_HPP
  27. /*
  28. Windows version of thread pool sockets with IO Completion Ports
  29. Included from <cat/net/ThreadPoolSockets.hpp>
  30. Do not include directly
  31. */
  32. #include <MSWSock.h>
  33. #include <cat/port/WindowsInclude.hpp>
  34. namespace cat {
  35. /*
  36. Thread Pool Sockets library
  37. Provides a framework for rapidly developing TCP/UDP server and client objects
  38. that make use of high performance APIs under various server and desktop
  39. operating systems.
  40. All network events are processed by a thread pool managed by ThreadPool.
  41. */
  42. class TCPServer;
  43. class TCPConnection;
  44. class TCPClient;
  45. class UDPEndpoint;
  46. //// Buffer Management
  47. // Generate a buffer to pass to Post()
  48. u8 *GetPostBuffer(u32 bytes);
  49. void *ResizePostBuffer(void *buffer, u32 newBytes);
  50. // Release a buffer provided by GetPostBuffer()
  51. // Note: Once the buffer is submitted to Post() this is unnecessary
  52. void ReleasePostBuffer(void *buffer);
  53. //// Overlapped Sockets
  54. // AcceptEx() OVERLAPPED structure
  55. struct AcceptExOverlapped
  56. {
  57. TypedOverlapped tov;
  58. Socket acceptSocket;
  59. // Space pre-allocated to receive addresses
  60. // NOTE: This is not necessarily how the addresses are organized in memory
  61. struct
  62. {
  63. // Not necessarily an IPv6 address either!
  64. sockaddr_in6 addr[2];
  65. u8 padding[2*16];
  66. } addresses;
  67. void Set(Socket s);
  68. };
  69. // WSARecvFrom() OVERLAPPED structure
  70. struct RecvFromOverlapped
  71. {
  72. TypedOverlapped tov;
  73. // Not necessarily and IPv6 address,
  74. // but we allocate enough space for one
  75. int addrLen;
  76. sockaddr_in6 addr;
  77. // data follows...
  78. void Reset();
  79. };
  80. /*
  81. class TCPServer
  82. Object that represents a TCP server bound to a single port
  83. Overload InstantiateServerConnection() to subclass connections with the server
  84. */
  85. class TCPServer : public ThreadRefObject
  86. {
  87. friend class TCPConnection;
  88. friend class ThreadPool;
  89. public:
  90. TCPServer();
  91. virtual ~TCPServer();
  92. bool ValidServer();
  93. Port GetPort();
  94. bool Bind(Port port = 0);
  95. void Close();
  96. protected:
  97. virtual TCPConnection *InstantiateServerConnection() = 0;
  98. private:
  99. Socket _socket;
  100. LPFN_ACCEPTEX _lpfnAcceptEx;
  101. LPFN_GETACCEPTEXSOCKADDRS _lpfnGetAcceptExSockAddrs;
  102. LPFN_DISCONNECTEX _lpfnDisconnectEx;
  103. Port _port;
  104. private:
  105. bool QueueAcceptEx();
  106. bool QueueAccepts();
  107. void OnAcceptExComplete(int error, AcceptExOverlapped *overlapped);
  108. };
  109. /*
  110. class TCPConnection
  111. Object that represents a TCPServer's connection from a TCPClient
  112. Object is instantiated just before accepting a connection
  113. DisconnectClient() : Disconnect the client
  114. PostToClient() : Send a message to the client
  115. ValidServerConnection() : Returns true iff the connection is valid
  116. OnConnectFromClient() : Return false to deny this connection
  117. OnReadFromClient() : Return false to disconnect the client in response to a message
  118. OnWriteToClient() : Informs the derived class that data has been sent
  119. OnDisconectFromClient() : Informs the derived class that the client has disconnected
  120. */
  121. class TCPConnection : public ThreadRefObject
  122. {
  123. friend class TCPServer;
  124. friend class ThreadPool;
  125. public:
  126. TCPConnection();
  127. virtual ~TCPConnection();
  128. bool ValidServerConnection();
  129. void DisconnectClient();
  130. bool PostToClient(void *buffer, u32 bytes);
  131. protected:
  132. virtual bool OnConnectFromClient(const NetAddr &remoteClientAddress) = 0; // false = disconnect
  133. virtual bool OnReadFromClient(u8 *data, u32 bytes) = 0; // false = disconnect
  134. virtual void OnWriteToClient(u32 bytes) = 0;
  135. virtual void OnDisconnectFromClient() = 0;
  136. private:
  137. Socket _socket;
  138. LPFN_DISCONNECTEX _lpfnDisconnectEx;
  139. TypedOverlapped *_recvOv;
  140. volatile u32 _disconnecting;
  141. private:
  142. bool AcceptConnection(Socket listenSocket, Socket acceptSocket,
  143. LPFN_DISCONNECTEX lpfnDisconnectEx, const NetAddr &acceptAddress,
  144. const NetAddr &remoteClientAddress);
  145. bool QueueWSARecv();
  146. void OnWSARecvComplete(int error, u32 bytes);
  147. bool QueueWSASend(TypedOverlapped *sendOv, u32 bytes);
  148. void OnWSASendComplete(int error, u32 bytes);
  149. bool QueueDisconnectEx();
  150. void OnDisconnectExComplete(int error);
  151. };
  152. /*
  153. class TCPClient
  154. Object that represents a TCPClient bound to a single port
  155. ValidClient() : Returns true iff the client socket is valid
  156. Connect() : Connects to the given address
  157. DisconnectServer() : Disconnects from the server
  158. PostToServer() : Send a message to the server (will fail if not connected)
  159. OnConnectToServer() : Called when connection is accepted
  160. OnReadFromServer() : Return false to disconnect the server in response to data
  161. OnWriteToServer() : Informs the derived class that data has been sent
  162. OnDisconnectFromServer() : Informs the derived class that the server has disconnected
  163. */
  164. class TCPClient : public ThreadRefObject
  165. {
  166. friend class ThreadPool;
  167. public:
  168. TCPClient();
  169. virtual ~TCPClient();
  170. bool ValidClient();
  171. bool Connect(const NetAddr &remoteServerAddress);
  172. void DisconnectServer();
  173. bool PostToServer(void *buffer, u32 bytes);
  174. protected:
  175. virtual void OnConnectToServer() = 0;
  176. virtual bool OnReadFromServer(u8 *data, u32 bytes) = 0; // false = disconnect
  177. virtual void OnWriteToServer(u32 bytes) = 0;
  178. virtual void OnDisconnectFromServer() = 0;
  179. private:
  180. Socket _socket;
  181. TypedOverlapped *_recvOv;
  182. volatile u32 _disconnecting;
  183. bool _ipv6;
  184. private:
  185. bool QueueConnectEx(const NetAddr &remoteServerAddress);
  186. void OnConnectExComplete(int error);
  187. bool QueueWSARecv();
  188. void OnWSARecvComplete(int error, u32 bytes);
  189. bool QueueWSASend(TypedOverlapped *sendOv, u32 bytes);
  190. void OnWSASendComplete(int error, u32 bytes);
  191. bool QueueDisconnectEx();
  192. void OnDisconnectExComplete(int error);
  193. };
  194. /*
  195. class TCPClientQueued
  196. Base class for a TCP client that needs to queue up data for sending before
  197. a connection has been established. e.g. Uplink for a proxy server.
  198. PostQueuedToServer() : Call in OnConnectToServer() to post the queued messages.
  199. */
  200. class TCPClientQueued : public TCPClient
  201. {
  202. private:
  203. volatile bool _queuing;
  204. Mutex _queueLock;
  205. void *_queueBuffer;
  206. u32 _queueBytes;
  207. protected:
  208. void PostQueuedToServer();
  209. public:
  210. TCPClientQueued();
  211. virtual ~TCPClientQueued();
  212. bool PostToServer(void *buffer, u32 bytes);
  213. };
  214. /*
  215. class UDPEndpoint
  216. Object that represents a UDP endpoint bound to a single port
  217. */
  218. class UDPEndpoint : public ThreadRefObject
  219. {
  220. friend class ThreadPool;
  221. public:
  222. UDPEndpoint();
  223. virtual ~UDPEndpoint();
  224. bool Valid();
  225. Port GetPort();
  226. // Is6() result is only valid AFTER Bind()
  227. CAT_INLINE bool Is6() { return _ipv6; }
  228. // For servers: Bind() with ignoreUnreachable = true ((default))
  229. // For clients: Bind() with ignoreUnreachable = false and call this
  230. // after the first packet from the server is received.
  231. bool IgnoreUnreachable();
  232. void Close(); // Invalidates this object
  233. bool Bind(Port port = 0, bool ignoreUnreachable = true);
  234. bool QueueWSARecvFrom();
  235. // If Is6() == true, the address must be promoted to IPv6
  236. // before calling Post() with addr.PromoteTo6()
  237. bool Post(const NetAddr &addr, void *data, u32 bytes);
  238. protected:
  239. virtual void OnRead(ThreadPoolLocalStorage *tls, const NetAddr &addr, u8 *data, u32 bytes) = 0; // false = close
  240. virtual void OnWrite(u32 bytes) = 0;
  241. virtual void OnClose() = 0;
  242. virtual void OnUnreachable(const NetAddr &addr) {} // Only IP is valid
  243. private:
  244. Socket _socket;
  245. Port _port;
  246. volatile u32 _closing;
  247. bool _ipv6;
  248. private:
  249. bool QueueWSARecvFrom(RecvFromOverlapped *recvOv);
  250. void OnWSARecvFromComplete(ThreadPoolLocalStorage *tls, int error, RecvFromOverlapped *recvOv, u32 bytes);
  251. bool QueueWSASendTo(const NetAddr &addr, TypedOverlapped *sendOv, u32 bytes);
  252. void OnWSASendToComplete(int error, u32 bytes);
  253. };
  254. } // namespace cat
  255. #endif // CAT_THREAD_POOL_SOCKETS_HPP
粤ICP备19079148号