socket.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/private/socket.h
  3. // Purpose: wxSocketImpl and related declarations
  4. // Authors: Guilhem Lavaux, Vadim Zeitlin
  5. // Created: April 1997
  6. // Copyright: (c) 1997 Guilhem Lavaux
  7. // (c) 2008 Vadim Zeitlin
  8. // Licence: wxWindows licence
  9. /////////////////////////////////////////////////////////////////////////////
  10. /*
  11. Brief overview of different socket classes:
  12. - wxSocketBase is the public class representing a socket ("Base" here
  13. refers to the fact that wxSocketClient and wxSocketServer are derived
  14. from it and predates the convention of using "Base" for common base
  15. classes for platform-specific classes in wxWidgets) with implementation
  16. common to all platforms and forwarding methods whose implementation
  17. differs between platforms to wxSocketImpl which it contains.
  18. - wxSocketImpl is actually just an abstract base class having only code
  19. common to all platforms, the concrete implementation classes derive from
  20. it and are created by wxSocketImpl::Create().
  21. - Some socket operations have different implementations in console-mode and
  22. GUI applications. wxSocketManager class exists to abstract this in such
  23. way that console applications (using wxBase) don't depend on wxNet. An
  24. object of this class is made available via wxApp and GUI applications set
  25. up a different kind of global socket manager from console ones.
  26. TODO: it looks like wxSocketManager could be eliminated by providing
  27. methods for registering/unregistering sockets directly in
  28. wxEventLoop.
  29. */
  30. #ifndef _WX_PRIVATE_SOCKET_H_
  31. #define _WX_PRIVATE_SOCKET_H_
  32. #include "wx/defs.h"
  33. #if wxUSE_SOCKETS
  34. #include "wx/socket.h"
  35. #include "wx/private/sckaddr.h"
  36. #include <stddef.h>
  37. /*
  38. Including sys/types.h under Cygwin results in the warnings about "fd_set
  39. having been defined in sys/types.h" when winsock.h is included later and
  40. doesn't seem to be necessary anyhow. It's not needed under Mac neither.
  41. */
  42. #if !defined(__WXMAC__) && !defined(__WXMSW__) && !defined(__WXWINCE__)
  43. #include <sys/types.h>
  44. #endif
  45. #ifdef __WXWINCE__
  46. #include <stdlib.h>
  47. #endif
  48. // include the header defining timeval: under Windows this struct is used only
  49. // with sockets so we need to include winsock.h which we do via windows.h
  50. #ifdef __WINDOWS__
  51. #include "wx/msw/wrapwin.h"
  52. #else
  53. #include <sys/time.h> // for timeval
  54. #endif
  55. // these definitions are for MSW when we don't use configure, otherwise these
  56. // symbols are defined by configure
  57. #ifndef WX_SOCKLEN_T
  58. #define WX_SOCKLEN_T int
  59. #endif
  60. #ifndef SOCKOPTLEN_T
  61. #define SOCKOPTLEN_T int
  62. #endif
  63. // define some symbols which winsock.h defines but traditional BSD headers
  64. // don't
  65. #ifndef INVALID_SOCKET
  66. #define INVALID_SOCKET (-1)
  67. #endif
  68. #ifndef SOCKET_ERROR
  69. #define SOCKET_ERROR (-1)
  70. #endif
  71. typedef int wxSocketEventFlags;
  72. class wxSocketImpl;
  73. /*
  74. Class providing hooks abstracting the differences between console and GUI
  75. applications for socket code.
  76. We also have different implementations of this class for different platforms
  77. allowing us to keep more things in the common code but the main reason for
  78. its existence is that we want the same socket code work differently
  79. depending on whether it's used from a console or a GUI program. This is
  80. achieved by implementing the virtual methods of this class differently in
  81. the objects returned by wxConsoleAppTraits::GetSocketManager() and the same
  82. method in wxGUIAppTraits.
  83. */
  84. class wxSocketManager
  85. {
  86. public:
  87. // set the manager to use, we don't take ownership of it
  88. //
  89. // this should be called before creating the first wxSocket object,
  90. // otherwise the manager returned by wxAppTraits::GetSocketManager() will
  91. // be used
  92. static void Set(wxSocketManager *manager);
  93. // return the manager to use
  94. //
  95. // this initializes the manager at first use
  96. static wxSocketManager *Get()
  97. {
  98. if ( !ms_manager )
  99. Init();
  100. return ms_manager;
  101. }
  102. // called before the first wxSocket is created and should do the
  103. // initializations needed in order to use the network
  104. //
  105. // return true if initialized successfully; if this returns false sockets
  106. // can't be used at all
  107. virtual bool OnInit() = 0;
  108. // undo the initializations of OnInit()
  109. virtual void OnExit() = 0;
  110. // create the socket implementation object matching this manager
  111. virtual wxSocketImpl *CreateSocket(wxSocketBase& wxsocket) = 0;
  112. // these functions enable or disable monitoring of the given socket for the
  113. // specified events inside the currently running event loop (but notice
  114. // that both BSD and Winsock implementations actually use socket->m_server
  115. // value to determine what exactly should be monitored so it needs to be
  116. // set before calling these functions)
  117. //
  118. // the default event value is used just for the convenience of wxMSW
  119. // implementation which doesn't use this parameter anyhow, it doesn't make
  120. // sense to pass wxSOCKET_LOST for the Unix implementation which does use
  121. // this parameter
  122. virtual void Install_Callback(wxSocketImpl *socket,
  123. wxSocketNotify event = wxSOCKET_LOST) = 0;
  124. virtual void Uninstall_Callback(wxSocketImpl *socket,
  125. wxSocketNotify event = wxSOCKET_LOST) = 0;
  126. virtual ~wxSocketManager() { }
  127. private:
  128. // get the manager to use if we don't have it yet
  129. static void Init();
  130. static wxSocketManager *ms_manager;
  131. };
  132. /*
  133. Base class for all socket implementations providing functionality common to
  134. BSD and Winsock sockets.
  135. Objects of this class are not created directly but only via the factory
  136. function wxSocketManager::CreateSocket().
  137. */
  138. class wxSocketImpl
  139. {
  140. public:
  141. virtual ~wxSocketImpl();
  142. // set various socket properties: all of those can only be called before
  143. // creating the socket
  144. void SetTimeout(unsigned long millisec);
  145. void SetReusable() { m_reusable = true; }
  146. void SetBroadcast() { m_broadcast = true; }
  147. void DontDoBind() { m_dobind = false; }
  148. void SetInitialSocketBuffers(int recv, int send)
  149. {
  150. m_initialRecvBufferSize = recv;
  151. m_initialSendBufferSize = send;
  152. }
  153. wxSocketError SetLocal(const wxSockAddressImpl& address);
  154. wxSocketError SetPeer(const wxSockAddressImpl& address);
  155. // accessors
  156. // ---------
  157. bool IsServer() const { return m_server; }
  158. const wxSockAddressImpl& GetLocal(); // non const as may update m_local
  159. const wxSockAddressImpl& GetPeer() const { return m_peer; }
  160. wxSocketError GetError() const { return m_error; }
  161. bool IsOk() const { return m_error == wxSOCKET_NOERROR; }
  162. // get the error code corresponding to the last operation
  163. virtual wxSocketError GetLastError() const = 0;
  164. // creating/closing the socket
  165. // --------------------------
  166. // notice that SetLocal() must be called before creating the socket using
  167. // any of the functions below
  168. //
  169. // all of Create() functions return wxSOCKET_NOERROR if the operation
  170. // completed successfully or one of:
  171. // wxSOCKET_INVSOCK - the socket is in use.
  172. // wxSOCKET_INVADDR - the local (server) or peer (client) address has not
  173. // been set.
  174. // wxSOCKET_IOERR - any other error.
  175. // create a socket listening on the local address specified by SetLocal()
  176. // (notice that DontDoBind() is ignored by this function)
  177. wxSocketError CreateServer();
  178. // create a socket connected to the peer address specified by SetPeer()
  179. // (notice that DontDoBind() is ignored by this function)
  180. //
  181. // this function may return wxSOCKET_WOULDBLOCK in addition to the return
  182. // values listed above if wait is false
  183. wxSocketError CreateClient(bool wait);
  184. // create (and bind unless DontDoBind() had been called) an UDP socket
  185. // associated with the given local address
  186. wxSocketError CreateUDP();
  187. // may be called whether the socket was created or not, calls DoClose() if
  188. // it was indeed created
  189. void Close();
  190. // shuts down the writing end of the socket and closes it, this is a more
  191. // graceful way to close
  192. //
  193. // does nothing if the socket wasn't created
  194. void Shutdown();
  195. // IO operations
  196. // -------------
  197. // basic IO, work for both TCP and UDP sockets
  198. //
  199. // return the number of bytes read/written (possibly 0) or -1 on error
  200. int Read(void *buffer, int size);
  201. int Write(const void *buffer, int size);
  202. // basically a wrapper for select(): returns the condition of the socket,
  203. // blocking for not longer than timeout if it is specified (otherwise just
  204. // poll without blocking at all)
  205. //
  206. // flags defines what kind of conditions we're interested in, the return
  207. // value is composed of a (possibly empty) subset of the bits set in flags
  208. wxSocketEventFlags Select(wxSocketEventFlags flags,
  209. const timeval *timeout = NULL);
  210. // convenient wrapper calling Select() with our default timeout
  211. wxSocketEventFlags SelectWithTimeout(wxSocketEventFlags flags)
  212. {
  213. return Select(flags, &m_timeout);
  214. }
  215. // just a wrapper for accept(): it is called to create a new wxSocketImpl
  216. // corresponding to a new server connection represented by the given
  217. // wxSocketBase, returns NULL on error (including immediately if there are
  218. // no pending connections as our sockets are non-blocking)
  219. wxSocketImpl *Accept(wxSocketBase& wxsocket);
  220. // notifications
  221. // -------------
  222. // notify m_wxsocket about the given socket event by calling its (inaptly
  223. // named) OnRequest() method
  224. void NotifyOnStateChange(wxSocketNotify event);
  225. // called after reading/writing the data from/to the socket and should
  226. // enable back the wxSOCKET_INPUT/OUTPUT_FLAG notifications if they were
  227. // turned off when this data was first detected
  228. virtual void ReenableEvents(wxSocketEventFlags flags) = 0;
  229. // TODO: make these fields protected and provide accessors for those of
  230. // them that wxSocketBase really needs
  231. //protected:
  232. wxSOCKET_T m_fd;
  233. int m_initialRecvBufferSize;
  234. int m_initialSendBufferSize;
  235. wxSockAddressImpl m_local,
  236. m_peer;
  237. wxSocketError m_error;
  238. bool m_stream;
  239. bool m_establishing;
  240. bool m_reusable;
  241. bool m_broadcast;
  242. bool m_dobind;
  243. struct timeval m_timeout;
  244. protected:
  245. wxSocketImpl(wxSocketBase& wxsocket);
  246. // true if we're a listening stream socket
  247. bool m_server;
  248. private:
  249. // called by Close() if we have a valid m_fd
  250. virtual void DoClose() = 0;
  251. // put this socket into non-blocking mode and enable monitoring this socket
  252. // as part of the event loop
  253. virtual void UnblockAndRegisterWithEventLoop() = 0;
  254. // check that the socket wasn't created yet and that the given address
  255. // (either m_local or m_peer depending on the socket kind) is valid and
  256. // set m_error and return false if this is not the case
  257. bool PreCreateCheck(const wxSockAddressImpl& addr);
  258. // set the given socket option: this just wraps setsockopt(SOL_SOCKET)
  259. int SetSocketOption(int optname, int optval)
  260. {
  261. // although modern Unix systems use "const void *" for the 4th
  262. // parameter here, old systems and Winsock still use "const char *"
  263. return setsockopt(m_fd, SOL_SOCKET, optname,
  264. reinterpret_cast<const char *>(&optval),
  265. sizeof(optval));
  266. }
  267. // set the given socket option to true value: this is an even simpler
  268. // wrapper for setsockopt(SOL_SOCKET) for boolean options
  269. int EnableSocketOption(int optname)
  270. {
  271. return SetSocketOption(optname, 1);
  272. }
  273. // apply the options to the (just created) socket and register it with the
  274. // event loop by calling UnblockAndRegisterWithEventLoop()
  275. void PostCreation();
  276. // update local address after binding/connecting
  277. wxSocketError UpdateLocalAddress();
  278. // functions used to implement Read/Write()
  279. int RecvStream(void *buffer, int size);
  280. int RecvDgram(void *buffer, int size);
  281. int SendStream(const void *buffer, int size);
  282. int SendDgram(const void *buffer, int size);
  283. // set in ctor and never changed except that it's reset to NULL when the
  284. // socket is shut down
  285. wxSocketBase *m_wxsocket;
  286. wxDECLARE_NO_COPY_CLASS(wxSocketImpl);
  287. };
  288. #if defined(__WINDOWS__)
  289. #include "wx/msw/private/sockmsw.h"
  290. #else
  291. #include "wx/unix/private/sockunix.h"
  292. #endif
  293. #endif /* wxUSE_SOCKETS */
  294. #endif /* _WX_PRIVATE_SOCKET_H_ */