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