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