PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/include/wx/socket.h

https://github.com/jay/wxWidgets
C Header | 435 lines | 246 code | 89 blank | 100 comment | 3 complexity | 46027f42d45f3b5b63547cb7a5caebe1 MD5 | raw file
Possible License(s): LGPL-3.0, AGPL-3.0, GPL-2.0, LGPL-2.0
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/socket.h
  3. // Purpose: Socket handling classes
  4. // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
  5. // Modified by:
  6. // Created: April 1997
  7. // Copyright: (c) Guilhem Lavaux
  8. // Licence: wxWindows licence
  9. /////////////////////////////////////////////////////////////////////////////
  10. #ifndef _WX_SOCKET_H_
  11. #define _WX_SOCKET_H_
  12. #include "wx/defs.h"
  13. #if wxUSE_SOCKETS
  14. // ---------------------------------------------------------------------------
  15. // wxSocket headers
  16. // ---------------------------------------------------------------------------
  17. #include "wx/event.h"
  18. #include "wx/sckaddr.h"
  19. #include "wx/list.h"
  20. class wxSocketImpl;
  21. // ------------------------------------------------------------------------
  22. // Types and constants
  23. // ------------------------------------------------------------------------
  24. // Define the type of native sockets.
  25. #if defined(__WINDOWS__)
  26. // Although socket descriptors are still 32 bit values, even under Win64,
  27. // the socket type is 64 bit there.
  28. typedef wxUIntPtr wxSOCKET_T;
  29. #else
  30. typedef int wxSOCKET_T;
  31. #endif
  32. // Types of different socket notifications or events.
  33. //
  34. // NB: the values here should be consecutive and start with 0 as they are
  35. // used to construct the wxSOCKET_XXX_FLAG bit mask values below
  36. enum wxSocketNotify
  37. {
  38. wxSOCKET_INPUT,
  39. wxSOCKET_OUTPUT,
  40. wxSOCKET_CONNECTION,
  41. wxSOCKET_LOST
  42. };
  43. enum
  44. {
  45. wxSOCKET_INPUT_FLAG = 1 << wxSOCKET_INPUT,
  46. wxSOCKET_OUTPUT_FLAG = 1 << wxSOCKET_OUTPUT,
  47. wxSOCKET_CONNECTION_FLAG = 1 << wxSOCKET_CONNECTION,
  48. wxSOCKET_LOST_FLAG = 1 << wxSOCKET_LOST
  49. };
  50. // this is a combination of the bit masks defined above
  51. typedef int wxSocketEventFlags;
  52. enum wxSocketError
  53. {
  54. wxSOCKET_NOERROR = 0,
  55. wxSOCKET_INVOP,
  56. wxSOCKET_IOERR,
  57. wxSOCKET_INVADDR,
  58. wxSOCKET_INVSOCK,
  59. wxSOCKET_NOHOST,
  60. wxSOCKET_INVPORT,
  61. wxSOCKET_WOULDBLOCK,
  62. wxSOCKET_TIMEDOUT,
  63. wxSOCKET_MEMERR,
  64. wxSOCKET_OPTERR
  65. };
  66. // socket options/flags bit masks
  67. enum
  68. {
  69. wxSOCKET_NONE = 0x0000,
  70. wxSOCKET_NOWAIT_READ = 0x0001,
  71. wxSOCKET_NOWAIT_WRITE = 0x0002,
  72. wxSOCKET_NOWAIT = wxSOCKET_NOWAIT_READ | wxSOCKET_NOWAIT_WRITE,
  73. wxSOCKET_WAITALL_READ = 0x0004,
  74. wxSOCKET_WAITALL_WRITE = 0x0008,
  75. wxSOCKET_WAITALL = wxSOCKET_WAITALL_READ | wxSOCKET_WAITALL_WRITE,
  76. wxSOCKET_BLOCK = 0x0010,
  77. wxSOCKET_REUSEADDR = 0x0020,
  78. wxSOCKET_BROADCAST = 0x0040,
  79. wxSOCKET_NOBIND = 0x0080
  80. };
  81. typedef int wxSocketFlags;
  82. // socket kind values (badly defined, don't use)
  83. enum wxSocketType
  84. {
  85. wxSOCKET_UNINIT,
  86. wxSOCKET_CLIENT,
  87. wxSOCKET_SERVER,
  88. wxSOCKET_BASE,
  89. wxSOCKET_DATAGRAM
  90. };
  91. // event
  92. class WXDLLIMPEXP_FWD_NET wxSocketEvent;
  93. wxDECLARE_EXPORTED_EVENT(WXDLLIMPEXP_NET, wxEVT_SOCKET, wxSocketEvent);
  94. // --------------------------------------------------------------------------
  95. // wxSocketBase
  96. // --------------------------------------------------------------------------
  97. class WXDLLIMPEXP_NET wxSocketBase : public wxObject
  98. {
  99. public:
  100. // Public interface
  101. // ----------------
  102. // ctors and dtors
  103. wxSocketBase();
  104. wxSocketBase(wxSocketFlags flags, wxSocketType type);
  105. virtual ~wxSocketBase();
  106. void Init();
  107. bool Destroy();
  108. // state
  109. bool Ok() const { return IsOk(); }
  110. bool IsOk() const { return m_impl != NULL; }
  111. bool Error() const { return LastError() != wxSOCKET_NOERROR; }
  112. bool IsClosed() const { return m_closed; }
  113. bool IsConnected() const { return m_connected; }
  114. bool IsData() { return WaitForRead(0, 0); }
  115. bool IsDisconnected() const { return !IsConnected(); }
  116. wxUint32 LastCount() const { return m_lcount; }
  117. wxUint32 LastReadCount() const { return m_lcount_read; }
  118. wxUint32 LastWriteCount() const { return m_lcount_write; }
  119. wxSocketError LastError() const;
  120. void SaveState();
  121. void RestoreState();
  122. // addresses
  123. virtual bool GetLocal(wxSockAddress& addr_man) const;
  124. virtual bool GetPeer(wxSockAddress& addr_man) const;
  125. virtual bool SetLocal(const wxIPV4address& local);
  126. // base IO
  127. virtual bool Close();
  128. void ShutdownOutput();
  129. wxSocketBase& Discard();
  130. wxSocketBase& Peek(void* buffer, wxUint32 nbytes);
  131. wxSocketBase& Read(void* buffer, wxUint32 nbytes);
  132. wxSocketBase& ReadMsg(void *buffer, wxUint32 nbytes);
  133. wxSocketBase& Unread(const void *buffer, wxUint32 nbytes);
  134. wxSocketBase& Write(const void *buffer, wxUint32 nbytes);
  135. wxSocketBase& WriteMsg(const void *buffer, wxUint32 nbytes);
  136. // all Wait() functions wait until their condition is satisfied or the
  137. // timeout expires; if seconds == -1 (default) then m_timeout value is used
  138. //
  139. // it is also possible to call InterruptWait() to cancel any current Wait()
  140. // wait for anything at all to happen with this socket
  141. bool Wait(long seconds = -1, long milliseconds = 0);
  142. // wait until we can read from or write to the socket without blocking
  143. // (notice that this does not mean that the operation will succeed but only
  144. // that it will return immediately)
  145. bool WaitForRead(long seconds = -1, long milliseconds = 0);
  146. bool WaitForWrite(long seconds = -1, long milliseconds = 0);
  147. // wait until the connection is terminated
  148. bool WaitForLost(long seconds = -1, long milliseconds = 0);
  149. void InterruptWait() { m_interrupt = true; }
  150. wxSocketFlags GetFlags() const { return m_flags; }
  151. void SetFlags(wxSocketFlags flags);
  152. virtual void SetTimeout(long seconds);
  153. long GetTimeout() const { return m_timeout; }
  154. bool GetOption(int level, int optname, void *optval, int *optlen);
  155. bool SetOption(int level, int optname, const void *optval, int optlen);
  156. wxUint32 GetLastIOSize() const { return m_lcount; }
  157. wxUint32 GetLastIOReadSize() const { return m_lcount_read; }
  158. wxUint32 GetLastIOWriteSize() const { return m_lcount_write; }
  159. // event handling
  160. void *GetClientData() const { return m_clientData; }
  161. void SetClientData(void *data) { m_clientData = data; }
  162. void SetEventHandler(wxEvtHandler& handler, int id = wxID_ANY);
  163. void SetNotify(wxSocketEventFlags flags);
  164. void Notify(bool notify);
  165. // Get the underlying socket descriptor.
  166. wxSOCKET_T GetSocket() const;
  167. // initialize/shutdown the sockets (done automatically so there is no need
  168. // to call these functions usually)
  169. //
  170. // should always be called from the main thread only so one of the cases
  171. // where they should indeed be called explicitly is when the first wxSocket
  172. // object in the application is created in a different thread
  173. static bool Initialize();
  174. static void Shutdown();
  175. // check if wxSocket had been already initialized
  176. //
  177. // notice that this function should be only called from the main thread as
  178. // otherwise it is inherently unsafe because Initialize/Shutdown() may be
  179. // called concurrently with it in the main thread
  180. static bool IsInitialized();
  181. // Implementation from now on
  182. // --------------------------
  183. // do not use, should be private (called from wxSocketImpl only)
  184. void OnRequest(wxSocketNotify notify);
  185. // do not use, not documented nor supported
  186. bool IsNoWait() const { return ((m_flags & wxSOCKET_NOWAIT) != 0); }
  187. wxSocketType GetType() const { return m_type; }
  188. private:
  189. friend class wxSocketClient;
  190. friend class wxSocketServer;
  191. friend class wxDatagramSocket;
  192. // low level IO
  193. wxUint32 DoRead(void* buffer, wxUint32 nbytes);
  194. wxUint32 DoWrite(const void *buffer, wxUint32 nbytes);
  195. // wait until the given flags are set for this socket or the given timeout
  196. // (or m_timeout) expires
  197. //
  198. // notice that wxSOCKET_LOST_FLAG is always taken into account and the
  199. // function returns -1 if the connection was lost; otherwise it returns
  200. // true if any of the events specified by flags argument happened or false
  201. // if the timeout expired
  202. int DoWait(long timeout, wxSocketEventFlags flags);
  203. // a helper calling DoWait() using the same convention as the public
  204. // WaitForXXX() functions use, i.e. use our timeout if seconds == -1 or the
  205. // specified timeout otherwise
  206. int DoWait(long seconds, long milliseconds, wxSocketEventFlags flags);
  207. // another helper calling DoWait() using our m_timeout
  208. int DoWaitWithTimeout(wxSocketEventFlags flags)
  209. {
  210. return DoWait(m_timeout*1000, flags);
  211. }
  212. // pushback buffer
  213. void Pushback(const void *buffer, wxUint32 size);
  214. wxUint32 GetPushback(void *buffer, wxUint32 size, bool peek);
  215. // store the given error as the LastError()
  216. void SetError(wxSocketError error);
  217. private:
  218. // socket
  219. wxSocketImpl *m_impl; // port-specific implementation
  220. wxSocketType m_type; // wxSocket type
  221. // state
  222. wxSocketFlags m_flags; // wxSocket flags
  223. bool m_connected; // connected?
  224. bool m_establishing; // establishing connection?
  225. bool m_reading; // busy reading?
  226. bool m_writing; // busy writing?
  227. bool m_closed; // was the other end closed?
  228. wxUint32 m_lcount; // last IO transaction size
  229. wxUint32 m_lcount_read; // last IO transaction size of Read() direction.
  230. wxUint32 m_lcount_write; // last IO transaction size of Write() direction.
  231. unsigned long m_timeout; // IO timeout value in seconds
  232. // (TODO: remove, wxSocketImpl has it too)
  233. wxList m_states; // stack of states (TODO: remove!)
  234. bool m_interrupt; // interrupt ongoing wait operations?
  235. bool m_beingDeleted; // marked for delayed deletion?
  236. wxIPV4address m_localAddress; // bind to local address?
  237. // pushback buffer
  238. void *m_unread; // pushback buffer
  239. wxUint32 m_unrd_size; // pushback buffer size
  240. wxUint32 m_unrd_cur; // pushback pointer (index into buffer)
  241. // events
  242. int m_id; // socket id
  243. wxEvtHandler *m_handler; // event handler
  244. void *m_clientData; // client data for events
  245. bool m_notify; // notify events to users?
  246. wxSocketEventFlags m_eventmask; // which events to notify?
  247. wxSocketEventFlags m_eventsgot; // collects events received in OnRequest()
  248. friend class wxSocketReadGuard;
  249. friend class wxSocketWriteGuard;
  250. wxDECLARE_NO_COPY_CLASS(wxSocketBase);
  251. DECLARE_CLASS(wxSocketBase)
  252. };
  253. // --------------------------------------------------------------------------
  254. // wxSocketServer
  255. // --------------------------------------------------------------------------
  256. class WXDLLIMPEXP_NET wxSocketServer : public wxSocketBase
  257. {
  258. public:
  259. wxSocketServer(const wxSockAddress& addr,
  260. wxSocketFlags flags = wxSOCKET_NONE);
  261. wxSocketBase* Accept(bool wait = true);
  262. bool AcceptWith(wxSocketBase& socket, bool wait = true);
  263. bool WaitForAccept(long seconds = -1, long milliseconds = 0);
  264. wxDECLARE_NO_COPY_CLASS(wxSocketServer);
  265. DECLARE_CLASS(wxSocketServer)
  266. };
  267. // --------------------------------------------------------------------------
  268. // wxSocketClient
  269. // --------------------------------------------------------------------------
  270. class WXDLLIMPEXP_NET wxSocketClient : public wxSocketBase
  271. {
  272. public:
  273. wxSocketClient(wxSocketFlags flags = wxSOCKET_NONE);
  274. virtual bool Connect(const wxSockAddress& addr, bool wait = true);
  275. bool Connect(const wxSockAddress& addr,
  276. const wxSockAddress& local,
  277. bool wait = true);
  278. bool WaitOnConnect(long seconds = -1, long milliseconds = 0);
  279. // Sets initial socket buffer sizes using the SO_SNDBUF and SO_RCVBUF
  280. // options before calling connect (either one can be -1 to leave it
  281. // unchanged)
  282. void SetInitialSocketBuffers(int recv, int send)
  283. {
  284. m_initialRecvBufferSize = recv;
  285. m_initialSendBufferSize = send;
  286. }
  287. private:
  288. virtual bool DoConnect(const wxSockAddress& addr,
  289. const wxSockAddress* local,
  290. bool wait = true);
  291. // buffer sizes, -1 if unset and defaults should be used
  292. int m_initialRecvBufferSize;
  293. int m_initialSendBufferSize;
  294. wxDECLARE_NO_COPY_CLASS(wxSocketClient);
  295. DECLARE_CLASS(wxSocketClient)
  296. };
  297. // --------------------------------------------------------------------------
  298. // wxDatagramSocket
  299. // --------------------------------------------------------------------------
  300. // WARNING: still in alpha stage
  301. class WXDLLIMPEXP_NET wxDatagramSocket : public wxSocketBase
  302. {
  303. public:
  304. wxDatagramSocket(const wxSockAddress& addr,
  305. wxSocketFlags flags = wxSOCKET_NONE);
  306. wxDatagramSocket& RecvFrom(wxSockAddress& addr,
  307. void *buf,
  308. wxUint32 nBytes);
  309. wxDatagramSocket& SendTo(const wxSockAddress& addr,
  310. const void* buf,
  311. wxUint32 nBytes);
  312. /* TODO:
  313. bool Connect(wxSockAddress& addr);
  314. */
  315. private:
  316. wxDECLARE_NO_COPY_CLASS(wxDatagramSocket);
  317. DECLARE_CLASS(wxDatagramSocket)
  318. };
  319. // --------------------------------------------------------------------------
  320. // wxSocketEvent
  321. // --------------------------------------------------------------------------
  322. class WXDLLIMPEXP_NET wxSocketEvent : public wxEvent
  323. {
  324. public:
  325. wxSocketEvent(int id = 0)
  326. : wxEvent(id, wxEVT_SOCKET)
  327. {
  328. }
  329. wxSocketNotify GetSocketEvent() const { return m_event; }
  330. wxSocketBase *GetSocket() const
  331. { return (wxSocketBase *) GetEventObject(); }
  332. void *GetClientData() const { return m_clientData; }
  333. virtual wxEvent *Clone() const wxOVERRIDE { return new wxSocketEvent(*this); }
  334. virtual wxEventCategory GetEventCategory() const wxOVERRIDE { return wxEVT_CATEGORY_SOCKET; }
  335. public:
  336. wxSocketNotify m_event;
  337. void *m_clientData;
  338. DECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxSocketEvent)
  339. };
  340. typedef void (wxEvtHandler::*wxSocketEventFunction)(wxSocketEvent&);
  341. #define wxSocketEventHandler(func) \
  342. wxEVENT_HANDLER_CAST(wxSocketEventFunction, func)
  343. #define EVT_SOCKET(id, func) \
  344. wx__DECLARE_EVT1(wxEVT_SOCKET, id, wxSocketEventHandler(func))
  345. #endif // wxUSE_SOCKETS
  346. #endif // _WX_SOCKET_H_