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