]> git.saurik.com Git - wxWidgets.git/blob - interface/wx/socket.h
Add A0 and A1 formats to wxPaperSize enumeration.
[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 Returns the pointer to the low-level representation of the address.
433
434 This can be used to pass socket address information to a 3rd party
435 library.
436
437 @return
438 Pointer to a sockaddr-derived struct.
439 */
440 const sockaddr *GetAddressData() const;
441
442 /**
443 Returns the length of the buffer retrieved by GetAddressData().
444
445 @return
446 The size of the sockaddr-derived struct corresponding to this
447 address.
448 */
449 int GetAddressDataLen() const;
450 };
451
452
453
454 /**
455 @class wxSocketEvent
456
457 This event class contains information about socket events.
458 This kind of events are sent to the event handler specified with
459 wxSocketBase::SetEventHandler.
460
461 @beginEventTable{wxSocketEvent}
462 @event{EVT_SOCKET(id, func)}
463 Process a socket event, supplying the member function.
464 @endEventTable
465
466 @library{wxnet}
467 @category{net}
468
469 @see wxSocketBase, wxSocketClient, wxSocketServer
470 */
471 class wxSocketEvent : public wxEvent
472 {
473 public:
474 /**
475 Constructor.
476 */
477 wxSocketEvent(int id = 0);
478
479 /**
480 Gets the client data of the socket which generated this event, as
481 set with wxSocketBase::SetClientData().
482 */
483 void* GetClientData() const;
484
485 /**
486 Returns the socket object to which this event refers to.
487 This makes it possible to use the same event handler for different sockets.
488 */
489 wxSocketBase* GetSocket() const;
490
491 /**
492 Returns the socket event type.
493 */
494 wxSocketNotify GetSocketEvent() const;
495 };
496
497
498 /**
499 wxSocket error return values.
500 */
501 enum wxSocketError
502 {
503 wxSOCKET_NOERROR, ///< No error happened.
504 wxSOCKET_INVOP, ///< Invalid operation.
505 wxSOCKET_IOERR, ///< Input/Output error.
506 wxSOCKET_INVADDR, ///< Invalid address passed to wxSocket.
507 wxSOCKET_INVSOCK, ///< Invalid socket (uninitialized).
508 wxSOCKET_NOHOST, ///< No corresponding host.
509 wxSOCKET_INVPORT, ///< Invalid port.
510 wxSOCKET_WOULDBLOCK, ///< The socket is non-blocking and the operation would block.
511 wxSOCKET_TIMEDOUT, ///< The timeout for this operation expired.
512 wxSOCKET_MEMERR ///< Memory exhausted.
513 };
514
515
516 /**
517 @anchor wxSocketEventFlags
518
519 wxSocket Event Flags.
520
521 A brief note on how to use these events:
522
523 The @b wxSOCKET_INPUT event will be issued whenever there is data available
524 for reading. This will be the case if the input queue was empty and new data
525 arrives, or if the application has read some data yet there is still more data
526 available. This means that the application does not need to read all available
527 data in response to a @b wxSOCKET_INPUT event, as more events will be produced
528 as necessary.
529
530 The @b wxSOCKET_OUTPUT event is issued when a socket is first connected with
531 Connect() or accepted with Accept(). After that, new events will be generated
532 only after an output operation fails with @b wxSOCKET_WOULDBLOCK and buffer space
533 becomes available again. This means that the application should assume that it can
534 write data to the socket until an @b wxSOCKET_WOULDBLOCK error occurs; after this,
535 whenever the socket becomes writable again the application will be notified with
536 another @b wxSOCKET_OUTPUT event.
537
538 The @b wxSOCKET_CONNECTION event is issued when a delayed connection request completes
539 successfully (client) or when a new connection arrives at the incoming queue (server).
540
541 The @b wxSOCKET_LOST event is issued when a close indication is received for the socket.
542 This means that the connection broke down or that it was closed by the peer. Also, this
543 event will be issued if a connection request fails.
544 */
545 enum wxSocketEventFlags
546 {
547 wxSOCKET_INPUT, ///< There is data available for reading.
548 wxSOCKET_OUTPUT, ///< The socket is ready to be written to.
549 wxSOCKET_CONNECTION, ///< Incoming connection request (server), or
550 ///< successful connection establishment (client).
551 wxSOCKET_LOST ///< The connection has been closed.
552 };
553
554
555 /**
556 @anchor wxSocketFlags
557
558 wxSocket Flags.
559
560 A brief overview on how to use these flags follows.
561
562 If no flag is specified (this is the same as @b wxSOCKET_NONE),
563 IO calls will return after some data has been read or written, even
564 when the transfer might not be complete. This is the same as issuing
565 exactly one blocking low-level call to @b recv() or @b send(). Note
566 that @e blocking here refers to when the function returns, not
567 to whether the GUI blocks during this time.
568
569 If @b wxSOCKET_NOWAIT is specified, IO calls will return immediately.
570 Read operations will retrieve only available data. Write operations will
571 write as much data as possible, depending on how much space is available
572 in the output buffer. This is the same as issuing exactly one nonblocking
573 low-level call to @b recv() or @b send(). Note that @e nonblocking here
574 refers to when the function returns, not to whether the GUI blocks during
575 this time.
576
577 If @b wxSOCKET_WAITALL is specified, IO calls won't return until ALL
578 the data has been read or written (or until an error occurs), blocking if
579 necessary, and issuing several low level calls if necessary. This is the
580 same as having a loop which makes as many blocking low-level calls to
581 @b recv() or @b send() as needed so as to transfer all the data. Note
582 that @e blocking here refers to when the function returns, not
583 to whether the GUI blocks during this time.
584
585 The @b wxSOCKET_BLOCK flag controls whether the GUI blocks during
586 IO operations. If this flag is specified, the socket will not yield
587 during IO calls, so the GUI will remain blocked until the operation
588 completes. If it is not used, then the application must take extra
589 care to avoid unwanted reentrance.
590
591 The @b wxSOCKET_REUSEADDR flag controls the use of the @b SO_REUSEADDR standard
592 @b setsockopt() flag. This flag allows the socket to bind to a port that is
593 already in use. This is mostly used on UNIX-based systems to allow rapid starting
594 and stopping of a server, otherwise you may have to wait several minutes for the
595 port to become available.
596
597 @b wxSOCKET_REUSEADDR can also be used with socket clients to (re)bind to a
598 particular local port for an outgoing connection.
599 This option can have surprising platform dependent behavior, so check the
600 documentation for your platform's implementation of setsockopt().
601
602 Note that on BSD-based systems(e.g. Mac OS X), use of
603 @b wxSOCKET_REUSEADDR implies @b SO_REUSEPORT in addition to
604 @b SO_REUSEADDR to be consistent with Windows.
605
606 The @b wxSOCKET_BROADCAST flag controls the use of the @b SO_BROADCAST standard
607 @b setsockopt() flag. This flag allows the socket to use the broadcast address,
608 and is generally used in conjunction with @b wxSOCKET_NOBIND and
609 wxIPaddress::BroadcastAddress().
610
611 So:
612 - @b wxSOCKET_NONE will try to read at least SOME data, no matter how much.
613 - @b wxSOCKET_NOWAIT will always return immediately, even if it cannot
614 read or write ANY data.
615 - @b wxSOCKET_WAITALL will only return when it has read or written ALL
616 the data.
617 - @b wxSOCKET_BLOCK has nothing to do with the previous flags and
618 it controls whether the GUI blocks.
619 - @b wxSOCKET_REUSEADDR controls special platform-specific behavior for
620 reusing local addresses/ports.
621 */
622 enum
623 {
624 wxSOCKET_NONE = 0, ///< Normal functionality.
625 wxSOCKET_NOWAIT = 1, ///< Read/write as much data as possible and return immediately.
626 wxSOCKET_WAITALL = 2, ///< Wait for all required data to be read/written unless an error occurs.
627 wxSOCKET_BLOCK = 4, ///< Block the GUI (do not yield) while reading/writing data.
628 wxSOCKET_REUSEADDR = 8, ///< Allows the use of an in-use port.
629 wxSOCKET_BROADCAST = 16, ///< Switches the socket to broadcast mode
630 wxSOCKET_NOBIND = 32 ///< Stops the socket from being bound to a specific
631 ///< adapter (normally used in conjunction with
632 ///< @b wxSOCKET_BROADCAST)
633 };
634
635
636 /**
637 @class wxSocketBase
638
639 wxSocketBase is the base class for all socket-related objects, and it
640 defines all basic IO functionality.
641
642 @note
643 When using wxSocket from multiple threads, even implicitly (e.g. by using
644 wxFTP or wxHTTP in another thread) you must initialize the sockets from the
645 main thread by calling Initialize() before creating the other ones.
646
647 @beginEventEmissionTable{wxSocketEvent}
648 @event{EVT_SOCKET(id, func)}
649 Process a @c wxEVT_SOCKET event.
650 See @ref wxSocketEventFlags and @ref wxSocketFlags for more info.
651 @endEventTable
652
653 @library{wxnet}
654 @category{net}
655
656 @see wxSocketEvent, wxSocketClient, wxSocketServer, @sample{sockets},
657 @ref wxSocketFlags, ::wxSocketEventFlags, ::wxSocketError
658 */
659 class wxSocketBase : public wxObject
660 {
661 public:
662
663 /**
664 @name Construction and Destruction
665 */
666 //@{
667
668 /**
669 Default constructor.
670
671 Don't use it directly; instead, use wxSocketClient to construct a socket client,
672 or wxSocketServer to construct a socket server.
673 */
674 wxSocketBase();
675
676 /**
677 Destructor.
678
679 Do not destroy a socket using the delete operator directly;
680 use Destroy() instead. Also, do not create socket objects in the stack.
681 */
682 virtual ~wxSocketBase();
683
684 /**
685 Destroys the socket safely.
686
687 Use this function instead of the delete operator, since otherwise socket events
688 could reach the application even after the socket has been destroyed. To prevent
689 this problem, this function appends the wxSocket to a list of object to be deleted
690 on idle time, after all events have been processed. For the same reason, you should
691 avoid creating socket objects in the stack.
692
693 Destroy() calls Close() automatically.
694
695 @return Always @true.
696 */
697 bool Destroy();
698
699 /**
700 Perform the initialization needed in order to use the sockets.
701
702 This function is called from wxSocket constructor implicitly and so
703 normally doesn't need to be called explicitly. There is however one
704 important exception: as this function must be called from the main
705 (UI) thread, if you use wxSocket from multiple threads you must call
706 Initialize() from the main thread before creating wxSocket objects in
707 the other ones.
708
709 It is safe to call this function multiple times (only the first call
710 does anything) but you must call Shutdown() exactly once for every call
711 to Initialize().
712
713 @return
714 @true if the sockets can be used, @false if the initialization
715 failed and sockets are not available at all.
716 */
717 static bool Initialize();
718
719 /**
720 Shut down the sockets.
721
722 This function undoes the call to Initialize() and must be called after
723 every successful call to Initialize().
724 */
725 static void Shutdown();
726
727 //@}
728
729
730 /**
731 @name Socket State
732 */
733 //@{
734
735 /**
736 Returns @true if an error occurred in the last IO operation.
737
738 Use this function to check for an error condition after one of the
739 following calls: Discard(), Peek(), Read(), ReadMsg(), Unread(), Write(), WriteMsg().
740 */
741 bool Error() const;
742
743 /**
744 Return the local address of the socket.
745
746 @return @true if no error happened, @false otherwise.
747 */
748 virtual bool GetLocal(wxSockAddress& addr) const;
749
750 /**
751 Return the peer address field of the socket.
752
753 @return @true if no error happened, @false otherwise.
754 */
755 virtual bool GetPeer(wxSockAddress& addr) const;
756
757 /**
758 Return the socket timeout in seconds.
759
760 The timeout can be set using SetTimeout() and is 10 minutes by default.
761 */
762 long GetTimeout() const;
763
764 /**
765 Returns @true if the socket is connected.
766 */
767 bool IsConnected() const;
768
769 /**
770 Check if the socket can be currently read or written.
771
772 This might mean that queued data is available for reading or, for streamed
773 sockets, that the connection has been closed, so that a read operation will
774 complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
775 is set, in which case the operation might still block).
776 */
777 bool IsData();
778
779 /**
780 Returns @true if the socket is not connected.
781 */
782 bool IsDisconnected() const;
783
784 /**
785 Returns @true if the socket is initialized and ready and @false in other
786 cases.
787
788 @remarks
789 For wxSocketClient, IsOk() won't return @true unless the client is connected to a server.
790 For wxSocketServer, IsOk() will return @true if the server could bind to the specified address
791 and is already listening for new connections.
792 IsOk() does not check for IO errors; use Error() instead for that purpose.
793 */
794 bool IsOk() const;
795
796 /**
797 Returns the number of bytes read or written by the last IO call.
798
799 Use this function to get the number of bytes actually transferred
800 after using one of the following IO calls: Discard(), Peek(), Read(),
801 ReadMsg(), Unread(), Write(), WriteMsg().
802 */
803 wxUint32 LastCount() const;
804
805 /**
806 Returns the last wxSocket error. See @ref wxSocketError .
807
808 @note
809 This function merely returns the last error code,
810 but it should not be used to determine if an error has occurred (this
811 is because successful operations do not change the LastError value).
812 Use Error() first, in order to determine if the last IO call failed.
813 If this returns @true, use LastError() to discover the cause of the error.
814 */
815 wxSocketError LastError() const;
816
817 /**
818 Restore the previous state of the socket, as saved with SaveState().
819
820 Calls to SaveState() and RestoreState() can be nested.
821
822 @see SaveState()
823 */
824 void RestoreState();
825
826 /**
827 Save the current state of the socket in a stack.
828
829 Socket state includes flags, as set with SetFlags(), event mask, as set
830 with SetNotify() and Notify(), user data, as set with SetClientData().
831 Calls to SaveState and RestoreState can be nested.
832
833 @see RestoreState()
834 */
835 void SaveState();
836
837 //@}
838
839
840 /**
841 @name Basic I/O
842
843 See also: wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
844 */
845 //@{
846
847 /**
848 Shut down the socket, disabling further transmission and reception of
849 data and disable events for the socket and frees the associated system
850 resources.
851
852 Upon socket destruction, Close() is automatically called, so in most cases
853 you won't need to do it yourself, unless you explicitly want to shut down
854 the socket, typically to notify the peer that you are closing the connection.
855
856 @remarks
857 Although Close() immediately disables events for the socket, it is possible
858 that event messages may be waiting in the application's event queue.
859 The application must therefore be prepared to handle socket event messages even
860 after calling Close().
861 */
862 virtual bool Close();
863
864 /**
865 Shuts down the writing end of the socket.
866
867 This function simply calls the standard shutdown() function on the
868 underlying socket, indicating that nothing will be written to this
869 socket any more.
870 */
871 void ShutdownOutput();
872
873 /**
874 Delete all bytes in the incoming queue.
875
876 This function always returns immediately and its operation is not
877 affected by IO flags.
878
879 Use LastCount() to verify the number of bytes actually discarded.
880
881 If you use Error(), it will always return @false.
882 */
883 wxSocketBase& Discard();
884
885 /**
886 Returns current IO flags, as set with SetFlags()
887 */
888 wxSocketFlags GetFlags() const;
889
890 /**
891 Use this function to interrupt any wait operation currently in progress.
892
893 Note that this is not intended as a regular way to interrupt a Wait call,
894 but only as an escape mechanism for exceptional situations where it is
895 absolutely necessary to use it, for example to abort an operation due to
896 some exception or abnormal problem. InterruptWait is automatically called
897 when you Close() a socket (and thus also upon
898 socket destruction), so you don't need to use it in these cases.
899
900 @see Wait(), WaitForLost(), WaitForRead(), WaitForWrite(),
901 wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
902 */
903 void InterruptWait();
904
905 /**
906 Peek into the socket by copying the next bytes which would be read by
907 Read() into the provided buffer.
908
909 Peeking a buffer doesn't delete it from the socket input queue, i.e.
910 calling Read() will return the same data.
911
912 Use LastCount() to verify the number of bytes actually peeked.
913
914 Use Error() to determine if the operation succeeded.
915
916 @param buffer
917 Buffer where to put peeked data.
918 @param nbytes
919 Number of bytes.
920
921 @return Returns a reference to the current object.
922
923 @remarks
924 The exact behaviour of Peek() depends on the combination of flags being used.
925 For a detailed explanation, see SetFlags()
926
927 @see Error(), LastError(), LastCount(), SetFlags()
928 */
929 wxSocketBase& Peek(void* buffer, wxUint32 nbytes);
930
931 /**
932 Read up to the given number of bytes from the socket.
933
934 Use LastCount() to verify the number of bytes actually read.
935 Use Error() to determine if the operation succeeded.
936
937 @param buffer
938 Buffer where to put read data.
939 @param nbytes
940 Number of bytes.
941
942 @return Returns a reference to the current object.
943
944 @remarks
945 The exact behaviour of Read() depends on the combination of flags being used.
946 For a detailed explanation, see SetFlags()
947
948 @see Error(), LastError(), LastCount(),
949 SetFlags()
950 */
951 wxSocketBase& Read(void* buffer, wxUint32 nbytes);
952
953 /**
954 Receive a message sent by WriteMsg().
955
956 If the buffer passed to the function isn't big enough, the remaining
957 bytes will be discarded. This function always waits for the buffer to
958 be entirely filled, unless an error occurs.
959
960 Use LastCount() to verify the number of bytes actually read.
961
962 Use Error() to determine if the operation succeeded.
963
964 @param buffer
965 Buffer where to put read data.
966 @param nbytes
967 Size of the buffer.
968
969 @return Returns a reference to the current object.
970
971 @remarks
972 ReadMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set
973 and it will always ignore the @b wxSOCKET_NOWAIT flag.
974 The exact behaviour of ReadMsg() depends on the @b wxSOCKET_BLOCK flag.
975 For a detailed explanation, see SetFlags().
976
977 @see Error(), LastError(), LastCount(), SetFlags(), WriteMsg()
978 */
979 wxSocketBase& ReadMsg(void* buffer, wxUint32 nbytes);
980
981 /**
982 Use SetFlags to customize IO operation for this socket.
983
984 The @a flags parameter may be a combination of flags ORed together.
985 Notice that not all combinations of flags affecting the IO calls
986 (Read() and Write()) make sense, e.g. @b wxSOCKET_NOWAIT can't be
987 combined with @b wxSOCKET_WAITALL nor with @b wxSOCKET_BLOCK.
988
989 The following flags can be used:
990 @beginFlagTable
991 @flag{wxSOCKET_NONE}
992 Default mode: the socket will read some data in the IO calls and
993 will process events to avoid blocking UI while waiting for the data
994 to become available.
995 @flag{wxSOCKET_NOWAIT}
996 Don't wait for the socket to become ready in IO calls, read as much
997 data as is available -- potentially 0 bytes -- and return
998 immediately.
999 @flag{wxSOCKET_WAITALL}
1000 Don't return before the entire amount of data specified in IO calls
1001 is read or written unless an error occurs. If this flag is not
1002 specified, the IO calls return as soon as any amount of data, even
1003 less than the total number of bytes, is processed.
1004 @flag{wxSOCKET_BLOCK}
1005 Don't process the UI events while waiting for the socket to become
1006 ready. This means that UI will be unresponsive during socket IO.
1007 @flag{wxSOCKET_REUSEADDR}
1008 Allows the use of an in-use port (wxServerSocket only).
1009 @flag{wxSOCKET_BROADCAST}
1010 Switches the socket to broadcast mode.
1011 @flag{wxSOCKET_NOBIND}
1012 Stops the socket from being bound to a specific adapter (normally
1013 used in conjunction with @b wxSOCKET_BROADCAST).
1014 @endFlagTable
1015
1016 For more information on socket events see @ref wxSocketFlags .
1017 */
1018 void SetFlags(wxSocketFlags flags);
1019
1020 /**
1021 Set the local address and port to use.
1022
1023 This function must always be called for the server sockets but may also
1024 be called for client sockets, if it is, @b bind() is called before @b
1025 connect().
1026 */
1027 virtual bool SetLocal(const wxIPV4address& local);
1028
1029 /**
1030 Set the default socket timeout in seconds.
1031
1032 This timeout applies to all IO calls, and also to the Wait() family of
1033 functions if you don't specify a wait interval. Initially, the default
1034 timeout is 10 minutes.
1035 */
1036 void SetTimeout(long seconds);
1037
1038 /**
1039 Put the specified data into the input queue.
1040
1041 The data in the buffer will be returned by the next call to Read().
1042
1043 This function is not affected by wxSocket flags.
1044
1045 If you use LastCount(), it will always return @a nbytes.
1046
1047 If you use Error(), it will always return @false.
1048
1049 @param buffer
1050 Buffer to be unread.
1051 @param nbytes
1052 Number of bytes.
1053
1054 @return Returns a reference to the current object.
1055
1056 @see Error(), LastCount(), LastError()
1057 */
1058 wxSocketBase& Unread(const void* buffer, wxUint32 nbytes);
1059
1060 /**
1061 Wait for any socket event.
1062
1063 Possible socket events are:
1064 @li The socket becomes readable.
1065 @li The socket becomes writable.
1066 @li An ongoing connection request has completed (wxSocketClient only)
1067 @li An incoming connection request has arrived (wxSocketServer only)
1068 @li The connection has been closed.
1069
1070 Note that it is recommended to use the individual @b WaitForXXX()
1071 functions to wait for the required condition, instead of this one.
1072
1073 @param seconds
1074 Number of seconds to wait.
1075 If -1, it will wait for the default timeout,
1076 as set with SetTimeout().
1077 @param millisecond
1078 Number of milliseconds to wait.
1079
1080 @return
1081 @true when any of the above conditions is satisfied or @false if the
1082 timeout was reached.
1083
1084 @see InterruptWait(), wxSocketServer::WaitForAccept(),
1085 WaitForLost(), WaitForRead(),
1086 WaitForWrite(), wxSocketClient::WaitOnConnect()
1087 */
1088 bool Wait(long seconds = -1, long millisecond = 0);
1089
1090 /**
1091 Wait until the connection is lost.
1092
1093 This may happen if the peer gracefully closes the connection or if the
1094 connection breaks.
1095
1096 @param seconds
1097 Number of seconds to wait.
1098 If -1, it will wait for the default timeout,
1099 as set with SetTimeout().
1100 @param millisecond
1101 Number of milliseconds to wait.
1102
1103 @return Returns @true if the connection was lost, @false if the timeout
1104 was reached.
1105
1106 @see InterruptWait(), Wait()
1107 */
1108 bool WaitForLost(long seconds = -1, long millisecond = 0);
1109
1110 /**
1111 Wait until the socket is readable.
1112
1113 This might mean that queued data is available for reading or, for streamed
1114 sockets, that the connection has been closed, so that a read operation will
1115 complete immediately without blocking (unless the @b wxSOCKET_WAITALL flag
1116 is set, in which case the operation might still block).
1117
1118 Notice that this function should not be called if there is already data
1119 available for reading on the socket.
1120
1121 @param seconds
1122 Number of seconds to wait.
1123 If -1, it will wait for the default timeout,
1124 as set with SetTimeout().
1125 @param millisecond
1126 Number of milliseconds to wait.
1127
1128 @return Returns @true if the socket becomes readable, @false on timeout.
1129
1130 @see InterruptWait(), Wait()
1131 */
1132 bool WaitForRead(long seconds = -1, long millisecond = 0);
1133
1134 /**
1135 Wait until the socket becomes writable.
1136
1137 This might mean that the socket is ready to send new data, or for streamed
1138 sockets, that the connection has been closed, so that a write operation is
1139 guaranteed to complete immediately (unless the @b wxSOCKET_WAITALL flag is set,
1140 in which case the operation might still block).
1141
1142 Notice that this function should not be called if the socket is already
1143 writable.
1144
1145 @param seconds
1146 Number of seconds to wait.
1147 If -1, it will wait for the default timeout,
1148 as set with SetTimeout().
1149 @param millisecond
1150 Number of milliseconds to wait.
1151
1152 @return Returns @true if the socket becomes writable, @false on timeout.
1153
1154 @see InterruptWait(), Wait()
1155 */
1156 bool WaitForWrite(long seconds = -1, long millisecond = 0);
1157
1158 /**
1159 Write up to the given number of bytes to the socket.
1160
1161 Use LastCount() to verify the number of bytes actually written.
1162
1163 Use Error() to determine if the operation succeeded.
1164
1165 @param buffer
1166 Buffer with the data to be sent.
1167 @param nbytes
1168 Number of bytes.
1169
1170 @return Returns a reference to the current object.
1171
1172 @remarks
1173
1174 The exact behaviour of Write() depends on the combination of flags being used.
1175 For a detailed explanation, see SetFlags().
1176
1177 @see Error(), LastError(), LastCount(), SetFlags()
1178 */
1179 wxSocketBase& Write(const void* buffer, wxUint32 nbytes);
1180
1181 /**
1182 Sends a buffer which can be read using ReadMsg().
1183
1184 WriteMsg() sends a short header before the data so that ReadMsg()
1185 knows how much data should be actually read.
1186
1187 This function always waits for the entire buffer to be sent, unless an
1188 error occurs.
1189
1190 Use LastCount() to verify the number of bytes actually written.
1191
1192 Use Error() to determine if the operation succeeded.
1193
1194 @param buffer
1195 Buffer with the data to be sent.
1196 @param nbytes
1197 Number of bytes to send.
1198
1199 @return Returns a reference to the current object.
1200
1201 @remarks
1202
1203 WriteMsg() will behave as if the @b wxSOCKET_WAITALL flag was always set and
1204 it will always ignore the @b wxSOCKET_NOWAIT flag. The exact behaviour of
1205 WriteMsg() depends on the @b wxSOCKET_BLOCK flag. For a detailed explanation,
1206 see SetFlags().
1207
1208 @see Error(), LastError(), LastCount(), SetFlags(), ReadMsg()
1209
1210 */
1211 wxSocketBase& WriteMsg(const void* buffer, wxUint32 nbytes);
1212
1213 //@}
1214
1215
1216 /**
1217 @name Handling Socket Events
1218 */
1219 //@{
1220
1221 /**
1222 Returns a pointer of the client data for this socket, as set with
1223 SetClientData()
1224 */
1225 void* GetClientData() const;
1226
1227 /**
1228 According to the @a notify value, this function enables
1229 or disables socket events. If @a notify is @true, the events
1230 configured with SetNotify() will
1231 be sent to the application. If @a notify is @false; no events
1232 will be sent.
1233 */
1234 void Notify(bool notify);
1235
1236 /**
1237 Sets user-supplied client data for this socket. All socket events will
1238 contain a pointer to this data, which can be retrieved with
1239 the wxSocketEvent::GetClientData() function.
1240 */
1241 void SetClientData(void* data);
1242
1243 /**
1244 Sets an event handler to be called when a socket event occurs. The
1245 handler will be called for those events for which notification is
1246 enabled with SetNotify() and
1247 Notify().
1248
1249 @param handler
1250 Specifies the event handler you want to use.
1251 @param id
1252 The id of socket event.
1253
1254 @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
1255 */
1256 void SetEventHandler(wxEvtHandler& handler, int id = -1);
1257
1258 /**
1259 Specifies which socket events are to be sent to the event handler.
1260 The @a flags parameter may be combination of flags ORed together. The
1261 following flags can be used:
1262
1263 @beginFlagTable
1264 @flag{wxSOCKET_INPUT_FLAG} to receive @b wxSOCKET_INPUT.
1265 @flag{wxSOCKET_OUTPUT_FLAG} to receive @b wxSOCKET_OUTPUT.
1266 @flag{wxSOCKET_CONNECTION_FLAG} to receive @b wxSOCKET_CONNECTION.
1267 @flag{wxSOCKET_LOST_FLAG} to receive @b wxSOCKET_LOST.
1268 @endFlagTable
1269
1270 For example:
1271
1272 @code
1273 sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
1274 sock.Notify(true);
1275 @endcode
1276
1277 In this example, the user will be notified about incoming socket data and
1278 whenever the connection is closed.
1279
1280 For more information on socket events see @ref wxSocketEventFlags .
1281 */
1282 void SetNotify(wxSocketEventFlags flags);
1283
1284 //@}
1285 };
1286
1287
1288
1289 /**
1290 @class wxDatagramSocket
1291
1292 @todo docme
1293
1294 @library{wxnet}
1295 @category{net}
1296 */
1297 class wxDatagramSocket : public wxSocketBase
1298 {
1299 public:
1300 /**
1301 Constructor.
1302
1303 @param addr
1304 The socket address.
1305 @param flags
1306 Socket flags (See wxSocketBase::SetFlags()).
1307 */
1308 wxDatagramSocket(const wxSockAddress& addr,
1309 wxSocketFlags flags = wxSOCKET_NONE);
1310
1311 /**
1312 Destructor. Please see wxSocketBase::Destroy().
1313 */
1314 virtual ~wxDatagramSocket();
1315
1316 /**
1317 Write a buffer of @a nbytes bytes to the socket.
1318
1319 Use wxSocketBase::LastCount() to verify the number of bytes actually wrote.
1320 Use wxSocketBase::Error() to determine if the operation succeeded.
1321
1322 @param address
1323 The address of the destination peer for this data.
1324 @param buffer
1325 Buffer where read data is.
1326 @param nbytes
1327 Number of bytes.
1328
1329 @return Returns a reference to the current object.
1330
1331 @see wxSocketBase::LastError(), wxSocketBase::SetFlags()
1332 */
1333 wxDatagramSocket& SendTo(const wxSockAddress& address,
1334 const void* buffer, wxUint32 nbytes);
1335 };
1336