PageRenderTime 62ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/interface/wx/socket.h

https://github.com/jay/wxWidgets
C Header | 1470 lines | 155 code | 116 blank | 1199 comment | 0 complexity | c11a049c30e7f74f40cef1f9920c4572 MD5 | raw file
Possible License(s): LGPL-3.0, AGPL-3.0, GPL-2.0, LGPL-2.0
  1. /////////////////////////////////////////////////////////////////////////////
  2. // Name: socket.h
  3. // Purpose: interface of wxIP*address, wxSocket* classes
  4. // Author: wxWidgets team
  5. // Licence: wxWindows licence
  6. /////////////////////////////////////////////////////////////////////////////
  7. /**
  8. The type of the native socket.
  9. Notice that the definition below is simplified and this type is not always
  10. int, e.g. it is a 64 bit integer type under Win64.
  11. @since 2.9.5
  12. */
  13. typedef int wxSOCKET_T;
  14. /**
  15. @class wxIPaddress
  16. wxIPaddress is an abstract base class for all internet protocol address
  17. objects. Currently, only wxIPV4address is implemented. An experimental
  18. implementation for IPV6, wxIPV6address, is being developed.
  19. @library{wxnet}
  20. @category{net}
  21. */
  22. class wxIPaddress : public wxSockAddress
  23. {
  24. public:
  25. /**
  26. Internally, this is the same as setting the IP address to @b INADDR_ANY.
  27. On IPV4 implementations, 0.0.0.0
  28. On IPV6 implementations, ::
  29. @return @true on success, @false if something went wrong.
  30. */
  31. bool AnyAddress();
  32. /**
  33. Internally, this is the same as setting the IP address to @b INADDR_BROADCAST.
  34. On IPV4 implementations, 255.255.255.255
  35. @return @true on success, @false if something went wrong.
  36. */
  37. virtual bool BroadcastAddress() = 0;
  38. /**
  39. Set the address to hostname, which can be a host name or an IP-style address
  40. in a format dependent on implementation.
  41. @return @true on success, @false if something goes wrong (invalid
  42. hostname or invalid IP address).
  43. */
  44. bool Hostname(const wxString& hostname);
  45. /**
  46. Returns the hostname which matches the IP address.
  47. */
  48. wxString Hostname() const;
  49. /**
  50. Returns a wxString containing the IP address.
  51. */
  52. virtual wxString IPAddress() const = 0;
  53. /**
  54. Determines if current address is set to localhost.
  55. @return @true if address is localhost, @false if internet address.
  56. */
  57. virtual bool IsLocalHost() const = 0;
  58. /**
  59. Set address to localhost.
  60. On IPV4 implementations, 127.0.0.1
  61. On IPV6 implementations, ::1
  62. @return @true on success, @false if something went wrong.
  63. */
  64. bool LocalHost();
  65. /**
  66. Set the port to that corresponding to the specified service.
  67. @return @true on success, @false if something goes wrong (invalid @a service).
  68. */
  69. bool Service(const wxString& service);
  70. /**
  71. Set the port to that corresponding to the specified service.
  72. @return @true on success, @false if something goes wrong (invalid @a service).
  73. */
  74. bool Service(unsigned short service);
  75. /**
  76. Returns the current service.
  77. */
  78. unsigned short Service() const;
  79. };
  80. /**
  81. @class wxIPV4address
  82. A class for working with IPv4 network addresses.
  83. @library{wxnet}
  84. @category{net}
  85. */
  86. class wxIPV4address : public wxIPaddress
  87. {
  88. public:
  89. /**
  90. Set address to any of the addresses of the current machine.
  91. Whenever possible, use this function instead of LocalHost(),
  92. as this correctly handles multi-homed hosts and avoids other small
  93. problems. Internally, this is the same as setting the IP address
  94. to @b INADDR_ANY.
  95. @return @true on success, @false if something went wrong.
  96. */
  97. bool AnyAddress();
  98. /**
  99. Set the address to hostname, which can be a host name or an IP-style address
  100. in dot notation(<tt>a.b.c.d</tt>).
  101. @return @true on success, @false if something goes wrong (invalid
  102. hostname or invalid IP address).
  103. */
  104. bool Hostname(const wxString& hostname);
  105. /**
  106. Returns the hostname which matches the IP address.
  107. */
  108. virtual wxString Hostname() const;
  109. /**
  110. Returns a wxString containing the IP address in dot quad (127.0.0.1) format.
  111. */
  112. virtual wxString IPAddress() const;
  113. /**
  114. Set address to localhost (127.0.0.1).
  115. Whenever possible, use AnyAddress() instead of this one, as that one will
  116. correctly handle multi-homed hosts and avoid other small problems.
  117. @return @true on success, @false if something went wrong.
  118. */
  119. bool LocalHost();
  120. /**
  121. Set the port to that corresponding to the specified @a service.
  122. @return @true on success, @false if something goes wrong (invalid @a service).
  123. */
  124. bool Service(const wxString& service);
  125. /**
  126. Set the port to that corresponding to the specified @a service.
  127. @return @true on success, @false if something goes wrong (invalid @a service).
  128. */
  129. bool Service(unsigned short service);
  130. /**
  131. Returns the current service.
  132. */
  133. unsigned short Service() const;
  134. };
  135. /**
  136. @class wxSocketServer
  137. @todo describe me.
  138. @library{wxnet}
  139. @category{net}
  140. */
  141. class wxSocketServer : public wxSocketBase
  142. {
  143. public:
  144. /**
  145. Constructs a new server and tries to bind to the specified @e address.
  146. Before trying to accept new connections, remember to test whether it succeeded
  147. with wxSocketBase:IsOk().
  148. @param address
  149. Specifies the local address for the server (e.g. port number).
  150. @param flags
  151. Socket flags (See wxSocketBase::SetFlags()).
  152. */
  153. wxSocketServer(const wxSockAddress& address,
  154. wxSocketFlags flags = wxSOCKET_NONE);
  155. /**
  156. Destructor (it doesn't close the accepted connections).
  157. */
  158. virtual ~wxSocketServer();
  159. /**
  160. Accepts an incoming connection request, and creates a new wxSocketBase
  161. object which represents the server-side of the connection.
  162. If @a wait is @true and there are no pending connections to be
  163. accepted, it will wait for the next incoming connection to
  164. arrive.
  165. @warning This method will block the GUI.
  166. If @a wait is @false, it will try to accept a pending connection
  167. if there is one, but it will always return immediately without blocking
  168. the GUI. If you want to use Accept() in this way, you can either check for
  169. incoming connections with WaitForAccept() or catch @b wxSOCKET_CONNECTION events,
  170. then call Accept() once you know that there is an incoming connection waiting
  171. to be accepted.
  172. @return Returns an opened socket connection, or @NULL if an error
  173. occurred or if the wait parameter was @false and there
  174. were no pending connections.
  175. @see WaitForAccept(), wxSocketBase::SetNotify(),
  176. wxSocketBase::Notify(), AcceptWith()
  177. */
  178. wxSocketBase* Accept(bool wait = true);
  179. /**
  180. Accept an incoming connection using the specified socket object.
  181. @param socket
  182. Socket to be initialized
  183. @param wait
  184. See Accept() for more info.
  185. @return Returns @true on success, or @false if an error occurred or
  186. if the wait parameter was @false and there were no pending
  187. connections.
  188. @see WaitForAccept(), wxSocketBase::SetNotify(),
  189. wxSocketBase::Notify(), Accept()
  190. */
  191. bool AcceptWith(wxSocketBase& socket, bool wait = true);
  192. /**
  193. Wait for an incoming connection.
  194. Use it if you want to call Accept() or AcceptWith() with @e wait set
  195. to @false, to detect when an incoming connection is waiting to be accepted.
  196. @param seconds
  197. Number of seconds to wait. If -1, it will wait for the default
  198. timeout, as set with wxSocketBase::SetTimeout().
  199. @param millisecond
  200. Number of milliseconds to wait.
  201. @return @true if an incoming connection arrived, @false if the timeout
  202. elapsed.
  203. @see Accept(), AcceptWith(), wxSocketBase::InterruptWait()
  204. */
  205. bool WaitForAccept(long seconds = -1, long millisecond = 0);
  206. };
  207. /**
  208. @class wxSocketClient
  209. @todo describe me.
  210. @library{wxnet}
  211. @category{net}
  212. */
  213. class wxSocketClient : public wxSocketBase
  214. {
  215. public:
  216. /**
  217. Constructor.
  218. @param flags
  219. Socket flags (See wxSocketBase::SetFlags())
  220. */
  221. wxSocketClient(wxSocketFlags flags = wxSOCKET_NONE);
  222. /**
  223. Destructor. Please see wxSocketBase::Destroy().
  224. */
  225. virtual ~wxSocketClient();
  226. /**
  227. Connects to a server using the specified address.
  228. If @a wait is @true, Connect() will wait until the connection
  229. completes.
  230. @warning This method will block the GUI.
  231. If @a wait is @false, Connect() will try to establish the connection
  232. and return immediately, without blocking the GUI. When used this way,
  233. even if Connect() returns @false, the connection request can be
  234. completed later. To detect this, use WaitOnConnect(), or catch
  235. @b wxSOCKET_CONNECTION events (for successful establishment) and
  236. @b wxSOCKET_LOST events (for connection failure).
  237. @param address
  238. Address of the server.
  239. @param wait
  240. If @true, waits for the connection to complete.
  241. @return @true if the connection is established and no error occurs.
  242. If @a wait was true, and Connect() returns @false, an error
  243. occurred and the connection failed.
  244. If @a wait was @false, and Connect() returns @false, you should
  245. still be prepared to handle the completion of this connection request,
  246. either with WaitOnConnect() or by watching wxSOCKET_CONNECTION
  247. and wxSOCKET_LOST events.
  248. @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
  249. */
  250. virtual bool Connect(const wxSockAddress& address, bool wait = true);
  251. /**
  252. Connects to a server using the specified address.
  253. If @a wait is @true, Connect() will wait until the connection
  254. completes. @b Warning: This will block the GUI.
  255. If @a wait is @false, Connect() will try to establish the connection
  256. and return immediately, without blocking the GUI. When used this way,
  257. even if Connect() returns @false, the connection request can be
  258. completed later. To detect this, use WaitOnConnect(), or catch
  259. @b wxSOCKET_CONNECTION events (for successful establishment) and
  260. @b wxSOCKET_LOST events (for connection failure).
  261. @param address
  262. Address of the server.
  263. @param local
  264. Bind to the specified local address and port before connecting.
  265. The local address and port can also be set using SetLocal(),
  266. and then using the 2-parameter Connect() method.
  267. @param wait
  268. If @true, waits for the connection to complete.
  269. @return @true if the connection is established and no error occurs.
  270. If @a wait was true, and Connect() returns @false, an error
  271. occurred and the connection failed.
  272. If @a wait was @false, and Connect() returns @false, you should
  273. still be prepared to handle the completion of this connection request,
  274. either with WaitOnConnect() or by watching wxSOCKET_CONNECTION
  275. and wxSOCKET_LOST events.
  276. @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
  277. */
  278. bool Connect(const wxSockAddress& address, const wxSockAddress& local,
  279. bool wait = true);
  280. /**
  281. Wait until a connection request completes, or until the specified timeout
  282. elapses. Use this function after issuing a call to Connect() with
  283. @e wait set to @false.
  284. @param seconds
  285. Number of seconds to wait.
  286. If -1, it will wait for the default timeout, as set with wxSocketBase::SetTimeout().
  287. @param milliseconds
  288. Number of milliseconds to wait.
  289. @return
  290. WaitOnConnect() returns @true if the connection request completes.
  291. This does not necessarily mean that the connection was
  292. successfully established; it might also happen that the
  293. connection was refused by the peer. Use wxSocketBase::IsConnected()
  294. to distinguish between these two situations.
  295. @n @n If the timeout elapses, WaitOnConnect() returns @false.
  296. @n @n These semantics allow code like this:
  297. @code
  298. // Issue the connection request
  299. client->Connect(addr, false);
  300. // Wait until the request completes or until we decide to give up
  301. bool waitmore = true;
  302. while ( !client->WaitOnConnect(seconds, millis) && waitmore )
  303. {
  304. // possibly give some feedback to the user,
  305. // and update waitmore as needed.
  306. }
  307. bool success = client->IsConnected();
  308. @endcode
  309. */
  310. bool WaitOnConnect(long seconds = -1, long milliseconds = 0);
  311. };
  312. /**
  313. @class wxSockAddress
  314. You are unlikely to need to use this class: only wxSocketBase uses it.
  315. @library{wxnet}
  316. @category{net}
  317. @see wxSocketBase, wxIPaddress, wxIPV4address
  318. */
  319. class wxSockAddress : public wxObject
  320. {
  321. public:
  322. /**
  323. Default constructor.
  324. */
  325. wxSockAddress();
  326. /**
  327. Default destructor.
  328. */
  329. virtual ~wxSockAddress();
  330. /**
  331. Delete all information about the address.
  332. */
  333. virtual void Clear();
  334. /**
  335. Returns the length of the socket address.
  336. */
  337. int SockAddrLen();
  338. /**
  339. Returns the pointer to the low-level representation of the address.
  340. This can be used to pass socket address information to a 3rd party
  341. library.
  342. @return
  343. Pointer to a sockaddr-derived struct.
  344. */
  345. const sockaddr *GetAddressData() const;
  346. /**
  347. Returns the length of the buffer retrieved by GetAddressData().
  348. @return
  349. The size of the sockaddr-derived struct corresponding to this
  350. address.
  351. */
  352. int GetAddressDataLen() const;
  353. };
  354. /**
  355. @class wxSocketEvent
  356. This event class contains information about socket events.
  357. This kind of events are sent to the event handler specified with
  358. wxSocketBase::SetEventHandler.
  359. @beginEventTable{wxSocketEvent}
  360. @event{EVT_SOCKET(id, func)}
  361. Process a socket event, supplying the member function.
  362. @endEventTable
  363. @library{wxnet}
  364. @category{net}
  365. @see wxSocketBase, wxSocketClient, wxSocketServer
  366. */
  367. class wxSocketEvent : public wxEvent
  368. {
  369. public:
  370. /**
  371. Constructor.
  372. */
  373. wxSocketEvent(int id = 0);
  374. /**
  375. Gets the client data of the socket which generated this event, as
  376. set with wxSocketBase::SetClientData().
  377. */
  378. void* GetClientData() const;
  379. /**
  380. Returns the socket object to which this event refers to.
  381. This makes it possible to use the same event handler for different sockets.
  382. */
  383. wxSocketBase* GetSocket() const;
  384. /**
  385. Returns the socket event type.
  386. */
  387. wxSocketNotify GetSocketEvent() const;
  388. };
  389. /**
  390. wxSocket error return values.
  391. */
  392. enum wxSocketError
  393. {
  394. wxSOCKET_NOERROR, ///< No error happened.
  395. wxSOCKET_INVOP, ///< Invalid operation.
  396. wxSOCKET_IOERR, ///< Input/Output error.
  397. wxSOCKET_INVADDR, ///< Invalid address passed to wxSocket.
  398. wxSOCKET_INVSOCK, ///< Invalid socket (uninitialized).
  399. wxSOCKET_NOHOST, ///< No corresponding host.
  400. wxSOCKET_INVPORT, ///< Invalid port.
  401. wxSOCKET_WOULDBLOCK, ///< The socket is non-blocking and the operation would block.
  402. wxSOCKET_TIMEDOUT, ///< The timeout for this operation expired.
  403. wxSOCKET_MEMERR ///< Memory exhausted.
  404. };
  405. /**
  406. @anchor wxSocketEventFlags
  407. wxSocket Event Flags.
  408. A brief note on how to use these events:
  409. The @b wxSOCKET_INPUT event will be issued whenever there is data available
  410. for reading. This will be the case if the input queue was empty and new data
  411. arrives, or if the application has read some data yet there is still more data
  412. available. This means that the application does not need to read all available
  413. data in response to a @b wxSOCKET_INPUT event, as more events will be produced
  414. as necessary.
  415. The @b wxSOCKET_OUTPUT event is issued when a socket is first connected with
  416. Connect() or accepted with Accept(). After that, new events will be generated
  417. only after an output operation fails with @b wxSOCKET_WOULDBLOCK and buffer space
  418. becomes available again. This means that the application should assume that it can
  419. write data to the socket until an @b wxSOCKET_WOULDBLOCK error occurs; after this,
  420. whenever the socket becomes writable again the application will be notified with
  421. another @b wxSOCKET_OUTPUT event.
  422. The @b wxSOCKET_CONNECTION event is issued when a delayed connection request completes
  423. successfully (client) or when a new connection arrives at the incoming queue (server).
  424. The @b wxSOCKET_LOST event is issued when a close indication is received for the socket.
  425. This means that the connection broke down or that it was closed by the peer. Also, this
  426. event will be issued if a connection request fails.
  427. */
  428. enum wxSocketEventFlags
  429. {
  430. wxSOCKET_INPUT, ///< There is data available for reading.
  431. wxSOCKET_OUTPUT, ///< The socket is ready to be written to.
  432. wxSOCKET_CONNECTION, ///< Incoming connection request (server), or
  433. ///< successful connection establishment (client).
  434. wxSOCKET_LOST ///< The connection has been closed.
  435. };
  436. /**
  437. @anchor wxSocketFlags
  438. wxSocket Flags.
  439. A brief overview on how to use these flags follows.
  440. If no flag is specified (this is the same as @b wxSOCKET_NONE),
  441. IO calls will return after some data has been read or written, even
  442. when the transfer might not be complete. This is the same as issuing
  443. exactly one blocking low-level call to @b recv() or @b send(). Note
  444. that @e blocking here refers to when the function returns, not
  445. to whether the GUI blocks during this time.
  446. If @b wxSOCKET_NOWAIT is specified, IO calls will return immediately.
  447. Read operations will retrieve only available data. Write operations will
  448. write as much data as possible, depending on how much space is available
  449. in the output buffer. This is the same as issuing exactly one nonblocking
  450. low-level call to @b recv() or @b send(). Note that @e nonblocking here
  451. refers to when the function returns, not to whether the GUI blocks during
  452. this time. Also note that this flag impacts both Read and Write
  453. operations. If it is desired to control Read independently of Write, for
  454. example you want no wait on Read(), but you do want to wait on Write(), then
  455. use wxSOCKET_NOWAIT_READ and wxSOCKET_NOWAIT_WRITE.
  456. If @b wxSOCKET_NOWAIT_READ (this flag is new since wxWidgets 2.9.5) is
  457. specified, Read operations will return immediately. Read operations will
  458. retrieve only available data. This is the same as issuing exactly one
  459. nonblocking low-level call to @b recv(). Note that @e nonblocking here
  460. refers to when the function returns, not to whether the GUI blocks during
  461. this time. This flag should not be enabled if ReadMsg() is going to be
  462. used (it will be ignored), if you do then thread-safety may be at risk.
  463. Note that wxSOCKET_NOWAIT_READ impacts only Read operations and does not
  464. impact Write operations, allowing Read and Write operations to be set
  465. differently.
  466. If @b wxSOCKET_NOWAIT_WRITE (this flag is new since wxWidgets 2.9.5) is
  467. specified, Write operations will return immediately. Write operations will
  468. write as much data as possible, depending on how much space is available in
  469. the output buffer. This is the same as issuing exactly one nonblocking
  470. low-level call to @b send(). Note that @e nonblocking here refers to when
  471. the function returns, not to whether the GUI blocks during this time. This
  472. flag should not be enabled if WriteMsg() is going to be used (it will be
  473. ignored), if you use it then thread safety may be at risk. Note that
  474. wxSOCKET_NOWAIT_WRITE impacts only Write operations and does not impact
  475. Write operations, allowing Read and Write operations to be set differently.
  476. If @b wxSOCKET_WAITALL is specified, IO calls won't return until ALL
  477. the data has been read or written (or until an error occurs), blocking if
  478. necessary, and issuing several low level calls if necessary. This is the
  479. same as having a loop which makes as many blocking low-level calls to
  480. @b recv() or @b send() as needed so as to transfer all the data. Note
  481. that @e blocking here refers to when the function returns, not
  482. to whether the GUI blocks during this time. Note that wxSOCKET_WAITALL
  483. impacts both Read and Write operations. If you desire to wait
  484. for all on just Read operations, but not on Write operations, (or vice versa),
  485. use wxSOCKET_WAITALL_READ or wxSOCKET_WAITALL_WRITE.
  486. If @b wxSOCKET_WAITALL_READ (this flag is new since wxWidgets 2.9.5) is
  487. specified, Read operations won't return until ALL the data has been read
  488. (or until an error occurs), blocking if necessary, and issuing several low
  489. level calls if necessary. This is the same as having a loop which makes as
  490. many blocking low-level calls to @b recv() as needed so as to transfer all
  491. the data. Note that @e blocking here refers to when the function returns,
  492. not to whether the GUI blocks during this time. Note that
  493. wxSOCKET_WAITALL_READ only has an impact on Read operations, and has no
  494. impact on Write operations, allowing Read and Write operations to have
  495. different settings.
  496. If @b wxSOCKET_WAITALL_WRITE (this flag is new since wxWidgets 2.9.5) is
  497. specified, Write() and WriteMsg() calls won't return until ALL the data has
  498. been written (or until an error occurs), blocking if necessary, and issuing
  499. several low level calls if necessary. This is the same as having a loop
  500. which makes as many blocking low-level calls to @b send() as needed so as
  501. to transfer all the data. Note that @e blocking here refers to when the
  502. function returns, not to whether the GUI blocks during this time. Note
  503. that wxSOCKET_WAITALL_WRITE only has an impact on Write operations, and has
  504. no impact on Read operations, allowing Read and Write operations to have
  505. different settings.
  506. The @b wxSOCKET_BLOCK flag controls whether the GUI blocks during
  507. IO operations. If this flag is specified, the socket will not yield
  508. during IO calls, so the GUI will remain blocked until the operation
  509. completes. If it is not used, then the application must take extra
  510. care to avoid unwanted reentrance.
  511. The @b wxSOCKET_REUSEADDR flag controls the use of the @b SO_REUSEADDR standard
  512. @b setsockopt() flag. This flag allows the socket to bind to a port that is
  513. already in use. This is mostly used on UNIX-based systems to allow rapid starting
  514. and stopping of a server, otherwise you may have to wait several minutes for the
  515. port to become available.
  516. @b wxSOCKET_REUSEADDR can also be used with socket clients to (re)bind to a
  517. particular local port for an outgoing connection.
  518. This option can have surprising platform dependent behaviour, so check the
  519. documentation for your platform's implementation of setsockopt().
  520. Note that on BSD-based systems(e.g. Mac OS X), use of
  521. @b wxSOCKET_REUSEADDR implies @b SO_REUSEPORT in addition to
  522. @b SO_REUSEADDR to be consistent with Windows.
  523. The @b wxSOCKET_BROADCAST flag controls the use of the @b SO_BROADCAST standard
  524. @b setsockopt() flag. This flag allows the socket to use the broadcast address,
  525. and is generally used in conjunction with @b wxSOCKET_NOBIND and
  526. wxIPaddress::BroadcastAddress().
  527. So:
  528. - @b wxSOCKET_NONE will try to read at least SOME data, no matter how much.
  529. - @b wxSOCKET_NOWAIT will always return immediately, even if it cannot
  530. read or write ANY data.
  531. - @b wxSOCKET_WAITALL will only return when it has read or written ALL
  532. the data.
  533. - @b wxSOCKET_BLOCK has nothing to do with the previous flags and
  534. it controls whether the GUI blocks.
  535. - @b wxSOCKET_REUSEADDR controls special platform-specific behaviour for
  536. reusing local addresses/ports.
  537. */
  538. enum
  539. {
  540. wxSOCKET_NONE = 0, ///< Normal functionality.
  541. wxSOCKET_NOWAIT = 1, ///< Read/write as much data as possible and return immediately.
  542. wxSOCKET_WAITALL = 2, ///< Wait for all required data to be read/written unless an error occurs.
  543. wxSOCKET_BLOCK = 4, ///< Block the GUI (do not yield) while reading/writing data.
  544. wxSOCKET_REUSEADDR = 8, ///< Allows the use of an in-use port.
  545. wxSOCKET_BROADCAST = 16, ///< Switches the socket to broadcast mode
  546. wxSOCKET_NOBIND = 32, ///< Stops the socket from being bound to a specific
  547. ///< adapter (normally used in conjunction with
  548. ///< @b wxSOCKET_BROADCAST)
  549. wxSOCKET_NOWAIT_READ = 64, ///< Read as much data as possible and return immediately
  550. wxSOCKET_WAITALL_READ = 128, ///< Wait for all required data to be read unless an error occurs.
  551. wxSOCKET_NOWAIT_WRITE = 256, ///< Write as much data as possible and return immediately
  552. wxSOCKET_WAITALL_WRITE = 512 ///< Wait for all required data to be written unless an error occurs.
  553. };
  554. /**
  555. @class wxSocketBase
  556. wxSocketBase is the base class for all socket-related objects, and it
  557. defines all basic IO functionality.
  558. @note
  559. When using wxSocket from multiple threads, even implicitly (e.g. by using
  560. wxFTP or wxHTTP in another thread) you must initialize the sockets from the
  561. main thread by calling Initialize() before creating the other ones.
  562. @beginEventEmissionTable{wxSocketEvent}
  563. @event{EVT_SOCKET(id, func)}
  564. Process a @c wxEVT_SOCKET event.
  565. See @ref wxSocketEventFlags and @ref wxSocketFlags for more info.
  566. @endEventTable
  567. @library{wxnet}
  568. @category{net}
  569. @see wxSocketEvent, wxSocketClient, wxSocketServer, @sample{sockets},
  570. @ref wxSocketFlags, ::wxSocketEventFlags, ::wxSocketError
  571. */
  572. class wxSocketBase : public wxObject
  573. {
  574. public:
  575. /**
  576. @name Construction and Destruction
  577. */
  578. //@{
  579. /**
  580. Default constructor.
  581. Don't use it directly; instead, use wxSocketClient to construct a socket client,
  582. or wxSocketServer to construct a socket server.
  583. */
  584. wxSocketBase();
  585. /**
  586. Destructor.
  587. Do not destroy a socket using the delete operator directly;
  588. use Destroy() instead. Also, do not create socket objects in the stack.
  589. */
  590. virtual ~wxSocketBase();
  591. /**
  592. Destroys the socket safely.
  593. Use this function instead of the delete operator, since otherwise socket events
  594. could reach the application even after the socket has been destroyed. To prevent
  595. this problem, this function appends the wxSocket to a list of object to be deleted
  596. on idle time, after all events have been processed. For the same reason, you should
  597. avoid creating socket objects in the stack.
  598. Destroy() calls Close() automatically.
  599. @return Always @true.
  600. */
  601. bool Destroy();
  602. /**
  603. Perform the initialization needed in order to use the sockets.
  604. This function is called from wxSocket constructor implicitly and so
  605. normally doesn't need to be called explicitly. There is however one
  606. important exception: as this function must be called from the main
  607. (UI) thread, if you use wxSocket from multiple threads you must call
  608. Initialize() from the main thread before creating wxSocket objects in
  609. the other ones.
  610. It is safe to call this function multiple times (only the first call
  611. does anything) but you must call Shutdown() exactly once for every call
  612. to Initialize().
  613. This function should only be called from the main thread.
  614. @return
  615. @true if the sockets can be used, @false if the initialization
  616. failed and sockets are not available at all.
  617. */
  618. static bool Initialize();
  619. /**
  620. Shut down the sockets.
  621. This function undoes the call to Initialize() and must be called after
  622. every successful call to Initialize().
  623. This function should only be called from the main thread, just as
  624. Initialize().
  625. */
  626. static void Shutdown();
  627. //@}
  628. /**
  629. @name Socket State
  630. */
  631. //@{
  632. /**
  633. Returns @true if an error occurred in the last IO operation.
  634. Use this function to check for an error condition after one of the
  635. following calls: Discard(), Peek(), Read(), ReadMsg(), Unread(), Write(), WriteMsg().
  636. */
  637. bool Error() const;
  638. /**
  639. Return the local address of the socket.
  640. @return @true if no error happened, @false otherwise.
  641. */
  642. virtual bool GetLocal(wxSockAddress& addr) const;
  643. /**
  644. Return the peer address field of the socket.
  645. @return @true if no error happened, @false otherwise.
  646. */
  647. virtual bool GetPeer(wxSockAddress& addr) const;
  648. /**
  649. Return the socket timeout in seconds.
  650. The timeout can be set using SetTimeout() and is 10 minutes by default.
  651. */
  652. long GetTimeout() const;
  653. /**
  654. Returns @true if the socket is connected.
  655. */
  656. bool IsConnected() const;
  657. /**
  658. Check if the socket can be currently read or written.
  659. This might mean that queued data is available for reading or, for streamed
  660. sockets, that the connection has been closed, so that a read operation will
  661. complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
  662. is set, in which case the operation might still block).
  663. */
  664. bool IsData();
  665. /**
  666. Returns @true if the socket is not connected.
  667. */
  668. bool IsDisconnected() const;
  669. /**
  670. Returns @true if the socket is initialized and ready and @false in other
  671. cases.
  672. @remarks
  673. For wxSocketClient, IsOk() won't return @true unless the client is connected to a server.
  674. For wxSocketServer, IsOk() will return @true if the server could bind to the specified address
  675. and is already listening for new connections.
  676. IsOk() does not check for IO errors; use Error() instead for that purpose.
  677. */
  678. bool IsOk() const;
  679. /**
  680. Returns the number of bytes read or written by the last IO call.
  681. Use this function to get the number of bytes actually transferred
  682. after using one of the following IO calls: Discard(), Peek(), Read(),
  683. ReadMsg(), Unread(), Write(), WriteMsg().
  684. @deprecated
  685. This function is kept mostly for backwards compatibility. Use
  686. LastReadCount() or LastWriteCount() instead. LastCount() is still
  687. needed for use with less commonly used functions: Discard(),
  688. Peek(), and Unread().
  689. */
  690. wxUint32 LastCount() const;
  691. /**
  692. Returns the number of bytes read by the last Read() or ReadMsg()
  693. call (receive direction only).
  694. This function is thread-safe, in case Read() is executed in a
  695. different thread than Write(). Use LastReadCount() instead of
  696. LastCount() for this reason.
  697. Unlike LastCount(), the functions Discard(), Peek(), and Unread()
  698. are currently not supported by LastReadCount().
  699. @since 2.9.5
  700. */
  701. wxUint32 LastReadCount() const;
  702. /**
  703. Returns the number of bytes written by the last Write() or WriteMsg()
  704. call (transmit direction only).
  705. This function is thread-safe, in case Write() is executed in a
  706. different thread than Read(). Use LastWriteCount() instead of
  707. LastCount() for this reason.
  708. @since 2.9.5
  709. */
  710. wxUint32 LastWriteCount() const;
  711. /**
  712. Returns the last wxSocket error. See @ref wxSocketError .
  713. @note
  714. This function merely returns the last error code,
  715. but it should not be used to determine if an error has occurred (this
  716. is because successful operations do not change the LastError value).
  717. Use Error() first, in order to determine if the last IO call failed.
  718. If this returns @true, use LastError() to discover the cause of the error.
  719. */
  720. wxSocketError LastError() const;
  721. /**
  722. Restore the previous state of the socket, as saved with SaveState().
  723. Calls to SaveState() and RestoreState() can be nested.
  724. @see SaveState()
  725. */
  726. void RestoreState();
  727. /**
  728. Save the current state of the socket in a stack.
  729. Socket state includes flags, as set with SetFlags(), event mask, as set
  730. with SetNotify() and Notify(), user data, as set with SetClientData().
  731. Calls to SaveState and RestoreState can be nested.
  732. @see RestoreState()
  733. */
  734. void SaveState();
  735. //@}
  736. /**
  737. @name Basic I/O
  738. See also: wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
  739. */
  740. //@{
  741. /**
  742. Shut down the socket, disabling further transmission and reception of
  743. data and disable events for the socket and frees the associated system
  744. resources.
  745. Upon socket destruction, Close() is automatically called, so in most cases
  746. you won't need to do it yourself, unless you explicitly want to shut down
  747. the socket, typically to notify the peer that you are closing the connection.
  748. @remarks
  749. Although Close() immediately disables events for the socket, it is possible
  750. that event messages may be waiting in the application's event queue.
  751. The application must therefore be prepared to handle socket event messages even
  752. after calling Close().
  753. */
  754. virtual bool Close();
  755. /**
  756. Shuts down the writing end of the socket.
  757. This function simply calls the standard shutdown() function on the
  758. underlying socket, indicating that nothing will be written to this
  759. socket any more.
  760. */
  761. void ShutdownOutput();
  762. /**
  763. Delete all bytes in the incoming queue.
  764. This function always returns immediately and its operation is not
  765. affected by IO flags.
  766. Use LastCount() to verify the number of bytes actually discarded.
  767. If you use Error(), it will always return @false.
  768. */
  769. wxSocketBase& Discard();
  770. /**
  771. Returns current IO flags, as set with SetFlags()
  772. */
  773. wxSocketFlags GetFlags() const;
  774. /**
  775. Use this function to interrupt any wait operation currently in progress.
  776. Note that this is not intended as a regular way to interrupt a Wait call,
  777. but only as an escape mechanism for exceptional situations where it is
  778. absolutely necessary to use it, for example to abort an operation due to
  779. some exception or abnormal problem. InterruptWait is automatically called
  780. when you Close() a socket (and thus also upon
  781. socket destruction), so you don't need to use it in these cases.
  782. @see Wait(), WaitForLost(), WaitForRead(), WaitForWrite(),
  783. wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
  784. */
  785. void InterruptWait();
  786. /**
  787. Peek into the socket by copying the next bytes which would be read by
  788. Read() into the provided buffer.
  789. Peeking a buffer doesn't delete it from the socket input queue, i.e.
  790. calling Read() will return the same data.
  791. Use LastCount() to verify the number of bytes actually peeked.
  792. Use Error() to determine if the operation succeeded.
  793. @param buffer
  794. Buffer where to put peeked data.
  795. @param nbytes
  796. Number of bytes.
  797. @return Returns a reference to the current object.
  798. @remarks
  799. The exact behaviour of Peek() depends on the combination of flags being used.
  800. For a detailed explanation, see SetFlags()
  801. @see Error(), LastError(), LastCount(), SetFlags()
  802. */
  803. wxSocketBase& Peek(void* buffer, wxUint32 nbytes);
  804. /**
  805. Read up to the given number of bytes from the socket.
  806. Use LastReadCount() to verify the number of bytes actually read.
  807. Use Error() to determine if the operation succeeded.
  808. @param buffer
  809. Buffer where to put read data.
  810. @param nbytes
  811. Number of bytes.
  812. @return Returns a reference to the current object.
  813. @remarks
  814. The exact behaviour of Read() depends on the combination of flags being used.
  815. For a detailed explanation, see SetFlags()
  816. @see Error(), LastError(), LastReadCount(),
  817. SetFlags()
  818. */
  819. wxSocketBase& Read(void* buffer, wxUint32 nbytes);
  820. /**
  821. Receive a message sent by WriteMsg().
  822. If the buffer passed to the function isn't big enough, the remaining
  823. bytes will be discarded. This function always waits for the buffer to
  824. be entirely filled, unless an error occurs.
  825. Use LastReadCount() to verify the number of bytes actually read.
  826. Use Error() to determine if the operation succeeded.
  827. @param buffer
  828. Buffer where to put read data.
  829. @param nbytes
  830. Size of the buffer.
  831. @return Returns a reference to the current object.
  832. @remarks
  833. ReadMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set
  834. and it will always ignore the @b wxSOCKET_NOWAIT flag.
  835. The exact behaviour of ReadMsg() depends on the @b wxSOCKET_BLOCK flag.
  836. For a detailed explanation, see SetFlags().
  837. For thread safety, in case ReadMsg() and WriteMsg() are called in
  838. different threads, it is a good idea to call
  839. SetFlags(wxSOCKET_WAITALL|wx_SOCKET_BLOCK) before the first calls
  840. to ReadMsg() and WriteMsg() in different threads, as each of these
  841. functions will call SetFlags() which performs read/modify/write. By
  842. setting these flags before the multi-threading, it will ensure that
  843. they don't get reset by thread race conditions.
  844. @see Error(), LastError(), LastReadCount(), SetFlags(), WriteMsg()
  845. */
  846. wxSocketBase& ReadMsg(void* buffer, wxUint32 nbytes);
  847. /**
  848. Use SetFlags to customize IO operation for this socket.
  849. The @a flags parameter may be a combination of flags ORed together.
  850. Notice that not all combinations of flags affecting the IO calls
  851. (Read() and Write()) make sense, e.g. @b wxSOCKET_NOWAIT can't be
  852. combined with @b wxSOCKET_WAITALL nor with @b wxSOCKET_BLOCK.
  853. The following flags can be used:
  854. @beginFlagTable
  855. @flag{wxSOCKET_NONE}
  856. Default mode: the socket will read some data in the IO calls and
  857. will process events to avoid blocking UI while waiting for the data
  858. to become available.
  859. @flag{wxSOCKET_NOWAIT}
  860. Don't wait for the socket to become ready in IO calls, read as much
  861. data as is available -- potentially 0 bytes -- and return
  862. immediately.
  863. @flag{wxSOCKET_WAITALL}
  864. Don't return before the entire amount of data specified in IO calls
  865. is read or written unless an error occurs. If this flag is not
  866. specified, the IO calls return as soon as any amount of data, even
  867. less than the total number of bytes, is processed.
  868. @flag{wxSOCKET_BLOCK}
  869. Don't process the UI events while waiting for the socket to become
  870. ready. This means that UI will be unresponsive during socket IO.
  871. @flag{wxSOCKET_REUSEADDR}
  872. Allows the use of an in-use port (wxServerSocket only).
  873. @flag{wxSOCKET_BROADCAST}
  874. Switches the socket to broadcast mode.
  875. @flag{wxSOCKET_NOBIND}
  876. Stops the socket from being bound to a specific adapter (normally
  877. used in conjunction with @b wxSOCKET_BROADCAST).
  878. @endFlagTable
  879. For more information on socket events see @ref wxSocketFlags .
  880. */
  881. void SetFlags(wxSocketFlags flags);
  882. /**
  883. Set the local address and port to use.
  884. This function must always be called for the server sockets but may also
  885. be called for client sockets, if it is, @b bind() is called before @b
  886. connect().
  887. */
  888. virtual bool SetLocal(const wxIPV4address& local);
  889. /**
  890. Set the default socket timeout in seconds.
  891. This timeout applies to all IO calls, and also to the Wait() family of
  892. functions if you don't specify a wait interval. Initially, the default
  893. timeout is 10 minutes.
  894. */
  895. void SetTimeout(long seconds);
  896. /**
  897. Put the specified data into the input queue.
  898. The data in the buffer will be returned by the next call to Read().
  899. This function is not affected by wxSocket flags.
  900. If you use LastCount(), it will always return @a nbytes.
  901. If you use Error(), it will always return @false.
  902. @param buffer
  903. Buffer to be unread.
  904. @param nbytes
  905. Number of bytes.
  906. @return Returns a reference to the current object.
  907. @see Error(), LastCount(), LastError()
  908. */
  909. wxSocketBase& Unread(const void* buffer, wxUint32 nbytes);
  910. /**
  911. Wait for any socket event.
  912. Possible socket events are:
  913. @li The socket becomes readable.
  914. @li The socket becomes writable.
  915. @li An ongoing connection request has completed (wxSocketClient only)
  916. @li An incoming connection request has arrived (wxSocketServer only)
  917. @li The connection has been closed.
  918. Note that it is recommended to use the individual @b WaitForXXX()
  919. functions to wait for the required condition, instead of this one.
  920. @param seconds
  921. Number of seconds to wait.
  922. If -1, it will wait for the default timeout,
  923. as set with SetTimeout().
  924. @param millisecond
  925. Number of milliseconds to wait.
  926. @return
  927. @true when any of the above conditions is satisfied or @false if the
  928. timeout was reached.
  929. @see InterruptWait(), wxSocketServer::WaitForAccept(),
  930. WaitForLost(), WaitForRead(),
  931. WaitForWrite(), wxSocketClient::WaitOnConnect()
  932. */
  933. bool Wait(long seconds = -1, long millisecond = 0);
  934. /**
  935. Wait until the connection is lost.
  936. This may happen if the peer gracefully closes the connection or if the
  937. connection breaks.
  938. @param seconds
  939. Number of seconds to wait.
  940. If -1, it will wait for the default timeout,
  941. as set with SetTimeout().
  942. @param millisecond
  943. Number of milliseconds to wait.
  944. @return Returns @true if the connection was lost, @false if the timeout
  945. was reached.
  946. @see InterruptWait(), Wait()
  947. */
  948. bool WaitForLost(long seconds = -1, long millisecond = 0);
  949. /**
  950. Wait until the socket is readable.
  951. This might mean that queued data is available for reading or, for streamed
  952. sockets, that the connection has been closed, so that a read operation will
  953. complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
  954. is set, in which case the operation might still block).
  955. Notice that this function should not be called if there is already data
  956. available for reading on the socket.
  957. @param seconds
  958. Number of seconds to wait.
  959. If -1, it will wait for the default timeout,
  960. as set with SetTimeout().
  961. @param millisecond
  962. Number of milliseconds to wait.
  963. @return Returns @true if the socket becomes readable, @false on timeout.
  964. @see InterruptWait(), Wait()
  965. */
  966. bool WaitForRead(long seconds = -1, long millisecond = 0);
  967. /**
  968. Wait until the socket becomes writable.
  969. This might mean that the socket is ready to send new data, or for streamed
  970. sockets, that the connection has been closed, so that a write operation is
  971. guaranteed to complete immediately (unless the @b wxSOCKET_WAITALL flag is set,
  972. in which case the operation might still block).
  973. Notice that this function should not be called if the socket is already
  974. writable.
  975. @param seconds
  976. Number of seconds to wait.
  977. If -1, it will wait for the default timeout,
  978. as set with SetTimeout().
  979. @param millisecond
  980. Number of milliseconds to wait.
  981. @return Returns @true if the socket becomes writable, @false on timeout.
  982. @see InterruptWait(), Wait()
  983. */
  984. bool WaitForWrite(long seconds = -1, long millisecond = 0);
  985. /**
  986. Write up to the given number of bytes to the socket.
  987. Use LastWriteCount() to verify the number of bytes actually written.
  988. Use Error() to determine if the operation succeeded.
  989. @param buffer
  990. Buffer with the data to be sent.
  991. @param nbytes
  992. Number of bytes.
  993. @return Returns a reference to the current object.
  994. @remarks
  995. The exact behaviour of Write() depends on the combination of flags being used.
  996. For a detailed explanation, see SetFlags().
  997. @see Error(), LastError(), LastWriteCount(), SetFlags()
  998. */
  999. wxSocketBase& Write(const void* buffer, wxUint32 nbytes);
  1000. /**
  1001. Sends a buffer which can be read using ReadMsg().
  1002. WriteMsg() sends a short header before the data so that ReadMsg()
  1003. knows how much data should be actually read.
  1004. This function always waits for the entire buffer to be sent, unless an
  1005. error occurs.
  1006. Use LastWriteCount() to verify the number of bytes actually written.
  1007. Use Error() to determine if the operation succeeded.
  1008. @param buffer
  1009. Buffer with the data to be sent.
  1010. @param nbytes
  1011. Number of bytes to send.
  1012. @return Returns a reference to the current object.
  1013. @remarks
  1014. WriteMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set and
  1015. it will always ignore the @b wxSOCKET_NOWAIT flag. The exact behaviour of
  1016. WriteMsg() depends on the @b wxSOCKET_BLOCK flag. For a detailed explanation,
  1017. see SetFlags().
  1018. For thread safety, in case ReadMsg() and WriteMsg() are called in
  1019. different threads, it is a good idea to call
  1020. @code SetFlags(wxSOCKET_WAITALL|wx_SOCKET_BLOCK) @endcode before the
  1021. first calls to ReadMsg() and WriteMsg() in different threads, as each
  1022. of these functions calls SetFlags() which performs read/modify/write.
  1023. By setting these flags before the multi-threading, it will ensure that
  1024. they don't get reset by thread race conditions.
  1025. @see Error(), LastError(), LastWriteCount(), SetFlags(), ReadMsg()
  1026. */
  1027. wxSocketBase& WriteMsg(const void* buffer, wxUint32 nbytes);
  1028. //@}
  1029. /**
  1030. @name Handling Socket Events
  1031. */
  1032. //@{
  1033. /**
  1034. Returns a pointer of the client data for this socket, as set with
  1035. SetClientData()
  1036. */
  1037. void* GetClientData() const;
  1038. /**
  1039. According to the @a notify value, this function enables
  1040. or disables socket events. If @a notify is @true, the events
  1041. configured with SetNotify() will
  1042. be sent to the application. If @a notify is @false; no events
  1043. will be sent.
  1044. */
  1045. void Notify(bool notify);
  1046. /**
  1047. Sets user-supplied client data for this socket. All socket events will
  1048. contain a pointer to this data, which can be retrieved with
  1049. the wxSocketEvent::GetClientData() function.
  1050. */
  1051. void SetClientData(void* data);
  1052. /**
  1053. Sets an event handler to be called when a socket event occurs. The
  1054. handler will be called for those events for which notification is
  1055. enabled with SetNotify() and
  1056. Notify().
  1057. @param handler
  1058. Specifies the event handler you want to use.
  1059. @param id
  1060. The id of socket event.
  1061. @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
  1062. */
  1063. void SetEventHandler(wxEvtHandler& handler, int id = -1);
  1064. /**
  1065. Specifies which socket events are to be sent to the event handler.
  1066. The @a flags parameter may be combination of flags ORed together. The
  1067. following flags can be used:
  1068. @beginFlagTable
  1069. @flag{wxSOCKET_INPUT_FLAG} to receive @b wxSOCKET_INPUT.
  1070. @flag{wxSOCKET_OUTPUT_FLAG} to receive @b wxSOCKET_OUTPUT.
  1071. @flag{wxSOCKET_CONNECTION_FLAG} to receive @b wxSOCKET_CONNECTION.
  1072. @flag{wxSOCKET_LOST_FLAG} to receive @b wxSOCKET_LOST.
  1073. @endFlagTable
  1074. For example:
  1075. @code
  1076. sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
  1077. sock.Notify(true);
  1078. @endcode
  1079. In this example, the user will be notified about incoming socket data and
  1080. whenever the connection is closed.
  1081. For more information on socket events see @ref wxSocketEventFlags .
  1082. */
  1083. void SetNotify(wxSocketEventFlags flags);
  1084. /**
  1085. Returns the native socket descriptor.
  1086. This is intended to use with rarely used specific platform features
  1087. that can only be accessed via the actual socket descriptor.
  1088. Do not use this for reading or writing data from or to the socket as
  1089. this would almost surely interfere with wxSocket code logic and result
  1090. in unexpected behaviour.
  1091. The socket must be successfully initialized, e.g. connected for client
  1092. sockets, before this method can be called.
  1093. @return Returns the native socket descriptor.
  1094. @since 2.9.5
  1095. */
  1096. wxSOCKET_T GetSocket() const;
  1097. //@}
  1098. };
  1099. /**
  1100. @class wxDatagramSocket
  1101. @todo docme
  1102. @library{wxnet}
  1103. @category{net}
  1104. */
  1105. class wxDatagramSocket : public wxSocketBase
  1106. {
  1107. public:
  1108. /**
  1109. Constructor.
  1110. @param addr
  1111. The socket address.
  1112. @param flags
  1113. Socket flags (See wxSocketBase::SetFlags()).
  1114. */
  1115. wxDatagramSocket(const wxSockAddress& addr,
  1116. wxSocketFlags flags = wxSOCKET_NONE);
  1117. /**
  1118. Destructor. Please see wxSocketBase::Destroy().
  1119. */
  1120. virtual ~wxDatagramSocket();
  1121. /**
  1122. Write a buffer of @a nbytes bytes to the socket.
  1123. Use wxSocketBase::LastWriteCount() to verify the number of bytes actually wrote.
  1124. Use wxSocketBase::Error() to determine if the operation succeeded.
  1125. @param address
  1126. The address of the destination peer for this data.
  1127. @param buffer
  1128. Buffer where read data is.
  1129. @param nbytes
  1130. Number of bytes.
  1131. @return Returns a reference to the current object.
  1132. @see wxSocketBase::LastError(), wxSocketBase::SetFlags()
  1133. */
  1134. wxDatagramSocket& SendTo(const wxSockAddress& address,
  1135. const void* buffer, wxUint32 nbytes);
  1136. };