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