]>
git.saurik.com Git - wxWidgets.git/blob - interface/wx/socket.h
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxIP*address, wxSocket* classes
4 // Author: wxWidgets team
6 // Licence: wxWindows licence
7 /////////////////////////////////////////////////////////////////////////////
11 The type of the native socket.
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.
18 typedef int wxSOCKET_T
;
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.
30 class wxIPaddress
: public wxSockAddress
34 Internally, this is the same as setting the IP address to @b INADDR_ANY.
36 On IPV4 implementations, 0.0.0.0
38 On IPV6 implementations, ::
40 @return @true on success, @false if something went wrong.
45 Internally, this is the same as setting the IP address to @b INADDR_BROADCAST.
47 On IPV4 implementations, 255.255.255.255
49 @return @true on success, @false if something went wrong.
51 virtual bool BroadcastAddress() = 0;
54 Set the address to hostname, which can be a host name or an IP-style address
55 in a format dependent on implementation.
57 @return @true on success, @false if something goes wrong (invalid
58 hostname or invalid IP address).
60 bool Hostname(const wxString
& hostname
);
63 Returns the hostname which matches the IP address.
65 wxString
Hostname() const;
68 Returns a wxString containing the IP address.
70 virtual wxString
IPAddress() const = 0;
73 Determines if current address is set to localhost.
75 @return @true if address is localhost, @false if internet address.
77 virtual bool IsLocalHost() const = 0;
80 Set address to localhost.
82 On IPV4 implementations, 127.0.0.1
84 On IPV6 implementations, ::1
86 @return @true on success, @false if something went wrong.
91 Set the port to that corresponding to the specified service.
93 @return @true on success, @false if something goes wrong (invalid @a service).
95 bool Service(const wxString
& service
);
98 Set the port to that corresponding to the specified service.
100 @return @true on success, @false if something goes wrong (invalid @a service).
102 bool Service(unsigned short service
);
105 Returns the current service.
107 unsigned short Service() const;
114 A class for working with IPv4 network addresses.
119 class wxIPV4address
: public wxIPaddress
123 Set address to any of the addresses of the current machine.
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
130 @return @true on success, @false if something went wrong.
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>).
138 @return @true on success, @false if something goes wrong (invalid
139 hostname or invalid IP address).
141 bool Hostname(const wxString
& hostname
);
144 Returns the hostname which matches the IP address.
146 virtual wxString
Hostname() const;
149 Returns a wxString containing the IP address in dot quad (127.0.0.1) format.
151 virtual wxString
IPAddress() const;
154 Set address to localhost (127.0.0.1).
156 Whenever possible, use AnyAddress() instead of this one, as that one will
157 correctly handle multi-homed hosts and avoid other small problems.
159 @return @true on success, @false if something went wrong.
164 Set the port to that corresponding to the specified @a service.
166 @return @true on success, @false if something goes wrong (invalid @a service).
168 bool Service(const wxString
& service
);
171 Set the port to that corresponding to the specified @a service.
173 @return @true on success, @false if something goes wrong (invalid @a service).
175 bool Service(unsigned short service
);
178 Returns the current service.
180 unsigned short Service() const;
186 @class wxSocketServer
193 class wxSocketServer
: public wxSocketBase
197 Constructs a new server and tries to bind to the specified @e address.
199 Before trying to accept new connections, remember to test whether it succeeded
200 with wxSocketBase:IsOk().
203 Specifies the local address for the server (e.g. port number).
205 Socket flags (See wxSocketBase::SetFlags()).
207 wxSocketServer(const wxSockAddress
& address
,
208 wxSocketFlags flags
= wxSOCKET_NONE
);
211 Destructor (it doesn't close the accepted connections).
213 virtual ~wxSocketServer();
216 Accepts an incoming connection request, and creates a new wxSocketBase
217 object which represents the server-side of the connection.
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
223 @warning This method will block the GUI.
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
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.
236 @see WaitForAccept(), wxSocketBase::SetNotify(),
237 wxSocketBase::Notify(), AcceptWith()
239 wxSocketBase
* Accept(bool wait
= true);
242 Accept an incoming connection using the specified socket object.
245 Socket to be initialized
247 See Accept() for more info.
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
253 @see WaitForAccept(), wxSocketBase::SetNotify(),
254 wxSocketBase::Notify(), Accept()
256 bool AcceptWith(wxSocketBase
& socket
, bool wait
= true);
259 Wait for an incoming connection.
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.
265 Number of seconds to wait. If -1, it will wait for the default
266 timeout, as set with wxSocketBase::SetTimeout().
268 Number of milliseconds to wait.
270 @return @true if an incoming connection arrived, @false if the timeout
273 @see Accept(), AcceptWith(), wxSocketBase::InterruptWait()
275 bool WaitForAccept(long seconds
= -1, long millisecond
= 0);
280 @class wxSocketClient
287 class wxSocketClient
: public wxSocketBase
294 Socket flags (See wxSocketBase::SetFlags())
296 wxSocketClient(wxSocketFlags flags
= wxSOCKET_NONE
);
299 Destructor. Please see wxSocketBase::Destroy().
301 virtual ~wxSocketClient();
304 Connects to a server using the specified address.
306 If @a wait is @true, Connect() will wait until the connection
309 @warning This method will block the GUI.
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).
319 Address of the server.
321 If @true, waits for the connection to complete.
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.
331 @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
333 virtual bool Connect(const wxSockAddress
& address
, bool wait
= true);
336 Connects to a server using the specified address.
338 If @a wait is @true, Connect() will wait until the connection
339 completes. @b Warning: This will block the GUI.
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).
349 Address of the server.
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.
355 If @true, waits for the connection to complete.
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.
365 @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
367 bool Connect(const wxSockAddress
& address
, const wxSockAddress
& local
,
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.
376 Number of seconds to wait.
377 If -1, it will wait for the default timeout, as set with wxSocketBase::SetTimeout().
379 Number of milliseconds to wait.
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:
390 // Issue the connection request
391 client->Connect(addr, false);
393 // Wait until the request completes or until we decide to give up
394 bool waitmore = true;
395 while ( !client->WaitOnConnect(seconds, millis) && waitmore )
397 // possibly give some feedback to the user,
398 // and update waitmore as needed.
400 bool success = client->IsConnected();
403 bool WaitOnConnect(long seconds
= -1, long milliseconds
= 0);
411 You are unlikely to need to use this class: only wxSocketBase uses it.
416 @see wxSocketBase, wxIPaddress, wxIPV4address
418 class wxSockAddress
: public wxObject
429 virtual ~wxSockAddress();
432 Delete all informations about the address.
434 virtual void Clear();
437 Returns the length of the socket address.
442 Returns the pointer to the low-level representation of the address.
444 This can be used to pass socket address information to a 3rd party
448 Pointer to a sockaddr-derived struct.
450 const sockaddr
*GetAddressData() const;
453 Returns the length of the buffer retrieved by GetAddressData().
456 The size of the sockaddr-derived struct corresponding to this
459 int GetAddressDataLen() const;
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.
471 @beginEventTable{wxSocketEvent}
472 @event{EVT_SOCKET(id, func)}
473 Process a socket event, supplying the member function.
479 @see wxSocketBase, wxSocketClient, wxSocketServer
481 class wxSocketEvent
: public wxEvent
487 wxSocketEvent(int id
= 0);
490 Gets the client data of the socket which generated this event, as
491 set with wxSocketBase::SetClientData().
493 void* GetClientData() const;
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.
499 wxSocketBase
* GetSocket() const;
502 Returns the socket event type.
504 wxSocketNotify
GetSocketEvent() const;
509 wxSocket error return values.
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.
527 @anchor wxSocketEventFlags
529 wxSocket Event Flags.
531 A brief note on how to use these events:
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
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.
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).
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.
555 enum wxSocketEventFlags
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.
566 @anchor wxSocketFlags
570 A brief overview on how to use these flags follows.
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.
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.
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
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.
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.
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
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
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.
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.
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().
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.
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().
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
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.
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.
703 wxSocketBase is the base class for all socket-related objects, and it
704 defines all basic IO functionality.
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.
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.
720 @see wxSocketEvent, wxSocketClient, wxSocketServer, @sample{sockets},
721 @ref wxSocketFlags, ::wxSocketEventFlags, ::wxSocketError
723 class wxSocketBase
: public wxObject
728 @name Construction and Destruction
735 Don't use it directly; instead, use wxSocketClient to construct a socket client,
736 or wxSocketServer to construct a socket server.
743 Do not destroy a socket using the delete operator directly;
744 use Destroy() instead. Also, do not create socket objects in the stack.
746 virtual ~wxSocketBase();
749 Destroys the socket safely.
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.
757 Destroy() calls Close() automatically.
759 @return Always @true.
764 Perform the initialization needed in order to use the sockets.
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
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
777 This function should only be called from the main thread.
780 @true if the sockets can be used, @false if the initialization
781 failed and sockets are not available at all.
783 static bool Initialize();
786 Shut down the sockets.
788 This function undoes the call to Initialize() and must be called after
789 every successful call to Initialize().
791 This function should only be called from the main thread, just as
794 static void Shutdown();
805 Returns @true if an error occurred in the last IO operation.
807 Use this function to check for an error condition after one of the
808 following calls: Discard(), Peek(), Read(), ReadMsg(), Unread(), Write(), WriteMsg().
813 Return the local address of the socket.
815 @return @true if no error happened, @false otherwise.
817 virtual bool GetLocal(wxSockAddress
& addr
) const;
820 Return the peer address field of the socket.
822 @return @true if no error happened, @false otherwise.
824 virtual bool GetPeer(wxSockAddress
& addr
) const;
827 Return the socket timeout in seconds.
829 The timeout can be set using SetTimeout() and is 10 minutes by default.
831 long GetTimeout() const;
834 Returns @true if the socket is connected.
836 bool IsConnected() const;
839 Check if the socket can be currently read or written.
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).
849 Returns @true if the socket is not connected.
851 bool IsDisconnected() const;
854 Returns @true if the socket is initialized and ready and @false in other
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.
866 Returns the number of bytes read or written by the last IO call.
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().
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().
878 wxUint32
LastCount() const;
881 Returns the number of bytes read by the last Read() or ReadMsg()
882 call (receive direction only).
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.
888 Unlike LastCount(), the functions Discard(), Peek(), and Unread()
889 are currently not supported by LastReadCount().
893 wxUint32
LastReadCount() const;
896 Returns the number of bytes written by the last Write() or WriteMsg()
897 call (transmit direction only).
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.
905 wxUint32
LastWriteCount() const;
908 Returns the last wxSocket error. See @ref wxSocketError .
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.
917 wxSocketError
LastError() const;
920 Restore the previous state of the socket, as saved with SaveState().
922 Calls to SaveState() and RestoreState() can be nested.
929 Save the current state of the socket in a stack.
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.
945 See also: wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
950 Shut down the socket, disabling further transmission and reception of
951 data and disable events for the socket and frees the associated system
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.
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().
964 virtual bool Close();
967 Shuts down the writing end of the socket.
969 This function simply calls the standard shutdown() function on the
970 underlying socket, indicating that nothing will be written to this
973 void ShutdownOutput();
976 Delete all bytes in the incoming queue.
978 This function always returns immediately and its operation is not
979 affected by IO flags.
981 Use LastCount() to verify the number of bytes actually discarded.
983 If you use Error(), it will always return @false.
985 wxSocketBase
& Discard();
988 Returns current IO flags, as set with SetFlags()
990 wxSocketFlags
GetFlags() const;
993 Use this function to interrupt any wait operation currently in progress.
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.
1002 @see Wait(), WaitForLost(), WaitForRead(), WaitForWrite(),
1003 wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
1005 void InterruptWait();
1008 Peek into the socket by copying the next bytes which would be read by
1009 Read() into the provided buffer.
1011 Peeking a buffer doesn't delete it from the socket input queue, i.e.
1012 calling Read() will return the same data.
1014 Use LastCount() to verify the number of bytes actually peeked.
1016 Use Error() to determine if the operation succeeded.
1019 Buffer where to put peeked data.
1023 @return Returns a reference to the current object.
1026 The exact behaviour of Peek() depends on the combination of flags being used.
1027 For a detailed explanation, see SetFlags()
1029 @see Error(), LastError(), LastCount(), SetFlags()
1031 wxSocketBase
& Peek(void* buffer
, wxUint32 nbytes
);
1034 Read up to the given number of bytes from the socket.
1036 Use LastReadCount() to verify the number of bytes actually read.
1037 Use Error() to determine if the operation succeeded.
1040 Buffer where to put read data.
1044 @return Returns a reference to the current object.
1047 The exact behaviour of Read() depends on the combination of flags being used.
1048 For a detailed explanation, see SetFlags()
1050 @see Error(), LastError(), LastReadCount(),
1053 wxSocketBase
& Read(void* buffer
, wxUint32 nbytes
);
1056 Receive a message sent by WriteMsg().
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.
1062 Use LastReadCount() to verify the number of bytes actually read.
1064 Use Error() to determine if the operation succeeded.
1067 Buffer where to put read data.
1071 @return Returns a reference to the current object.
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.
1086 @see Error(), LastError(), LastReadCount(), SetFlags(), WriteMsg()
1088 wxSocketBase
& ReadMsg(void* buffer
, wxUint32 nbytes
);
1091 Use SetFlags to customize IO operation for this socket.
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.
1098 The following flags can be used:
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
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).
1125 For more information on socket events see @ref wxSocketFlags .
1127 void SetFlags(wxSocketFlags flags
);
1130 Set the local address and port to use.
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
1136 virtual bool SetLocal(const wxIPV4address
& local
);
1139 Set the default socket timeout in seconds.
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.
1145 void SetTimeout(long seconds
);
1148 Put the specified data into the input queue.
1150 The data in the buffer will be returned by the next call to Read().
1152 This function is not affected by wxSocket flags.
1154 If you use LastCount(), it will always return @a nbytes.
1156 If you use Error(), it will always return @false.
1159 Buffer to be unread.
1163 @return Returns a reference to the current object.
1165 @see Error(), LastCount(), LastError()
1167 wxSocketBase
& Unread(const void* buffer
, wxUint32 nbytes
);
1170 Wait for any socket event.
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.
1179 Note that it is recommended to use the individual @b WaitForXXX()
1180 functions to wait for the required condition, instead of this one.
1183 Number of seconds to wait.
1184 If -1, it will wait for the default timeout,
1185 as set with SetTimeout().
1187 Number of milliseconds to wait.
1190 @true when any of the above conditions is satisfied or @false if the
1191 timeout was reached.
1193 @see InterruptWait(), wxSocketServer::WaitForAccept(),
1194 WaitForLost(), WaitForRead(),
1195 WaitForWrite(), wxSocketClient::WaitOnConnect()
1197 bool Wait(long seconds
= -1, long millisecond
= 0);
1200 Wait until the connection is lost.
1202 This may happen if the peer gracefully closes the connection or if the
1206 Number of seconds to wait.
1207 If -1, it will wait for the default timeout,
1208 as set with SetTimeout().
1210 Number of milliseconds to wait.
1212 @return Returns @true if the connection was lost, @false if the timeout
1215 @see InterruptWait(), Wait()
1217 bool WaitForLost(long seconds
= -1, long millisecond
= 0);
1220 Wait until the socket is readable.
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).
1227 Notice that this function should not be called if there is already data
1228 available for reading on the socket.
1231 Number of seconds to wait.
1232 If -1, it will wait for the default timeout,
1233 as set with SetTimeout().
1235 Number of milliseconds to wait.
1237 @return Returns @true if the socket becomes readable, @false on timeout.
1239 @see InterruptWait(), Wait()
1241 bool WaitForRead(long seconds
= -1, long millisecond
= 0);
1244 Wait until the socket becomes writable.
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).
1251 Notice that this function should not be called if the socket is already
1255 Number of seconds to wait.
1256 If -1, it will wait for the default timeout,
1257 as set with SetTimeout().
1259 Number of milliseconds to wait.
1261 @return Returns @true if the socket becomes writable, @false on timeout.
1263 @see InterruptWait(), Wait()
1265 bool WaitForWrite(long seconds
= -1, long millisecond
= 0);
1268 Write up to the given number of bytes to the socket.
1270 Use LastWriteCount() to verify the number of bytes actually written.
1272 Use Error() to determine if the operation succeeded.
1275 Buffer with the data to be sent.
1279 @return Returns a reference to the current object.
1283 The exact behaviour of Write() depends on the combination of flags being used.
1284 For a detailed explanation, see SetFlags().
1286 @see Error(), LastError(), LastWriteCount(), SetFlags()
1288 wxSocketBase
& Write(const void* buffer
, wxUint32 nbytes
);
1291 Sends a buffer which can be read using ReadMsg().
1293 WriteMsg() sends a short header before the data so that ReadMsg()
1294 knows how much data should be actually read.
1296 This function always waits for the entire buffer to be sent, unless an
1299 Use LastWriteCount() to verify the number of bytes actually written.
1301 Use Error() to determine if the operation succeeded.
1304 Buffer with the data to be sent.
1306 Number of bytes to send.
1308 @return Returns a reference to the current object.
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,
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.
1324 @see Error(), LastError(), LastWriteCount(), SetFlags(), ReadMsg()
1327 wxSocketBase
& WriteMsg(const void* buffer
, wxUint32 nbytes
);
1333 @name Handling Socket Events
1338 Returns a pointer of the client data for this socket, as set with
1341 void* GetClientData() const;
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
1350 void Notify(bool notify
);
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.
1357 void SetClientData(void* data
);
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
1366 Specifies the event handler you want to use.
1368 The id of socket event.
1370 @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
1372 void SetEventHandler(wxEvtHandler
& handler
, int id
= -1);
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:
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.
1389 sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
1393 In this example, the user will be notified about incoming socket data and
1394 whenever the connection is closed.
1396 For more information on socket events see @ref wxSocketEventFlags .
1398 void SetNotify(wxSocketEventFlags flags
);
1401 Returns the native socket descriptor.
1403 This is intended to use with rarely used specific platform features
1404 that can only be accessed via the actual socket descriptor.
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.
1410 The socket must be successfully initialized, e.g. connected for client
1411 sockets, before this method can be called.
1413 @return Returns the native socket descriptor.
1417 wxSOCKET_T
GetSocket() const;
1425 @class wxDatagramSocket
1432 class wxDatagramSocket
: public wxSocketBase
1441 Socket flags (See wxSocketBase::SetFlags()).
1443 wxDatagramSocket(const wxSockAddress
& addr
,
1444 wxSocketFlags flags
= wxSOCKET_NONE
);
1447 Destructor. Please see wxSocketBase::Destroy().
1449 virtual ~wxDatagramSocket();
1452 Write a buffer of @a nbytes bytes to the socket.
1454 Use wxSocketBase::LastWriteCount() to verify the number of bytes actually wrote.
1455 Use wxSocketBase::Error() to determine if the operation succeeded.
1458 The address of the destination peer for this data.
1460 Buffer where read data is.
1464 @return Returns a reference to the current object.
1466 @see wxSocketBase::LastError(), wxSocketBase::SetFlags()
1468 wxDatagramSocket
& SendTo(const wxSockAddress
& address
,
1469 const void* buffer
, wxUint32 nbytes
);