PageRenderTime 62ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/wxWidgets/interface/wx/socket.h

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