]>
git.saurik.com Git - wxWidgets.git/blob - interface/wx/socket.h
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxIP*address, wxSocket* classes
4 // Author: wxWidgets team
5 // Licence: wxWindows licence
6 /////////////////////////////////////////////////////////////////////////////
10 The type of the native socket.
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.
17 typedef int wxSOCKET_T
;
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.
29 class wxIPaddress
: public wxSockAddress
33 Internally, this is the same as setting the IP address to @b INADDR_ANY.
35 On IPV4 implementations, 0.0.0.0
37 On IPV6 implementations, ::
39 @return @true on success, @false if something went wrong.
44 Internally, this is the same as setting the IP address to @b INADDR_BROADCAST.
46 On IPV4 implementations, 255.255.255.255
48 @return @true on success, @false if something went wrong.
50 virtual bool BroadcastAddress() = 0;
53 Set the address to hostname, which can be a host name or an IP-style address
54 in a format dependent on implementation.
56 @return @true on success, @false if something goes wrong (invalid
57 hostname or invalid IP address).
59 bool Hostname(const wxString
& hostname
);
62 Returns the hostname which matches the IP address.
64 wxString
Hostname() const;
67 Returns a wxString containing the IP address.
69 virtual wxString
IPAddress() const = 0;
72 Determines if current address is set to localhost.
74 @return @true if address is localhost, @false if internet address.
76 virtual bool IsLocalHost() const = 0;
79 Set address to localhost.
81 On IPV4 implementations, 127.0.0.1
83 On IPV6 implementations, ::1
85 @return @true on success, @false if something went wrong.
90 Set the port to that corresponding to the specified service.
92 @return @true on success, @false if something goes wrong (invalid @a service).
94 bool Service(const wxString
& service
);
97 Set the port to that corresponding to the specified service.
99 @return @true on success, @false if something goes wrong (invalid @a service).
101 bool Service(unsigned short service
);
104 Returns the current service.
106 unsigned short Service() const;
113 A class for working with IPv4 network addresses.
118 class wxIPV4address
: public wxIPaddress
122 Set address to any of the addresses of the current machine.
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
129 @return @true on success, @false if something went wrong.
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>).
137 @return @true on success, @false if something goes wrong (invalid
138 hostname or invalid IP address).
140 bool Hostname(const wxString
& hostname
);
143 Returns the hostname which matches the IP address.
145 virtual wxString
Hostname() const;
148 Returns a wxString containing the IP address in dot quad (127.0.0.1) format.
150 virtual wxString
IPAddress() const;
153 Set address to localhost (127.0.0.1).
155 Whenever possible, use AnyAddress() instead of this one, as that one will
156 correctly handle multi-homed hosts and avoid other small problems.
158 @return @true on success, @false if something went wrong.
163 Set the port to that corresponding to the specified @a service.
165 @return @true on success, @false if something goes wrong (invalid @a service).
167 bool Service(const wxString
& service
);
170 Set the port to that corresponding to the specified @a service.
172 @return @true on success, @false if something goes wrong (invalid @a service).
174 bool Service(unsigned short service
);
177 Returns the current service.
179 unsigned short Service() const;
185 @class wxSocketServer
192 class wxSocketServer
: public wxSocketBase
196 Constructs a new server and tries to bind to the specified @e address.
198 Before trying to accept new connections, remember to test whether it succeeded
199 with wxSocketBase:IsOk().
202 Specifies the local address for the server (e.g. port number).
204 Socket flags (See wxSocketBase::SetFlags()).
206 wxSocketServer(const wxSockAddress
& address
,
207 wxSocketFlags flags
= wxSOCKET_NONE
);
210 Destructor (it doesn't close the accepted connections).
212 virtual ~wxSocketServer();
215 Accepts an incoming connection request, and creates a new wxSocketBase
216 object which represents the server-side of the connection.
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
222 @warning This method will block the GUI.
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
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.
235 @see WaitForAccept(), wxSocketBase::SetNotify(),
236 wxSocketBase::Notify(), AcceptWith()
238 wxSocketBase
* Accept(bool wait
= true);
241 Accept an incoming connection using the specified socket object.
244 Socket to be initialized
246 See Accept() for more info.
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
252 @see WaitForAccept(), wxSocketBase::SetNotify(),
253 wxSocketBase::Notify(), Accept()
255 bool AcceptWith(wxSocketBase
& socket
, bool wait
= true);
258 Wait for an incoming connection.
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.
264 Number of seconds to wait. If -1, it will wait for the default
265 timeout, as set with wxSocketBase::SetTimeout().
267 Number of milliseconds to wait.
269 @return @true if an incoming connection arrived, @false if the timeout
272 @see Accept(), AcceptWith(), wxSocketBase::InterruptWait()
274 bool WaitForAccept(long seconds
= -1, long millisecond
= 0);
279 @class wxSocketClient
286 class wxSocketClient
: public wxSocketBase
293 Socket flags (See wxSocketBase::SetFlags())
295 wxSocketClient(wxSocketFlags flags
= wxSOCKET_NONE
);
298 Destructor. Please see wxSocketBase::Destroy().
300 virtual ~wxSocketClient();
303 Connects to a server using the specified address.
305 If @a wait is @true, Connect() will wait until the connection
308 @warning This method will block the GUI.
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).
318 Address of the server.
320 If @true, waits for the connection to complete.
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.
330 @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
332 virtual bool Connect(const wxSockAddress
& address
, bool wait
= true);
335 Connects to a server using the specified address.
337 If @a wait is @true, Connect() will wait until the connection
338 completes. @b Warning: This will block the GUI.
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).
348 Address of the server.
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.
354 If @true, waits for the connection to complete.
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.
364 @see WaitOnConnect(), wxSocketBase::SetNotify(), wxSocketBase::Notify()
366 bool Connect(const wxSockAddress
& address
, const wxSockAddress
& local
,
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.
375 Number of seconds to wait.
376 If -1, it will wait for the default timeout, as set with wxSocketBase::SetTimeout().
378 Number of milliseconds to wait.
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:
389 // Issue the connection request
390 client->Connect(addr, false);
392 // Wait until the request completes or until we decide to give up
393 bool waitmore = true;
394 while ( !client->WaitOnConnect(seconds, millis) && waitmore )
396 // possibly give some feedback to the user,
397 // and update waitmore as needed.
399 bool success = client->IsConnected();
402 bool WaitOnConnect(long seconds
= -1, long milliseconds
= 0);
410 You are unlikely to need to use this class: only wxSocketBase uses it.
415 @see wxSocketBase, wxIPaddress, wxIPV4address
417 class wxSockAddress
: public wxObject
428 virtual ~wxSockAddress();
431 Delete all informations about the address.
433 virtual void Clear();
436 Returns the length of the socket address.
441 Returns the pointer to the low-level representation of the address.
443 This can be used to pass socket address information to a 3rd party
447 Pointer to a sockaddr-derived struct.
449 const sockaddr
*GetAddressData() const;
452 Returns the length of the buffer retrieved by GetAddressData().
455 The size of the sockaddr-derived struct corresponding to this
458 int GetAddressDataLen() const;
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.
470 @beginEventTable{wxSocketEvent}
471 @event{EVT_SOCKET(id, func)}
472 Process a socket event, supplying the member function.
478 @see wxSocketBase, wxSocketClient, wxSocketServer
480 class wxSocketEvent
: public wxEvent
486 wxSocketEvent(int id
= 0);
489 Gets the client data of the socket which generated this event, as
490 set with wxSocketBase::SetClientData().
492 void* GetClientData() const;
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.
498 wxSocketBase
* GetSocket() const;
501 Returns the socket event type.
503 wxSocketNotify
GetSocketEvent() const;
508 wxSocket error return values.
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.
526 @anchor wxSocketEventFlags
528 wxSocket Event Flags.
530 A brief note on how to use these events:
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
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.
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).
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.
554 enum wxSocketEventFlags
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.
565 @anchor wxSocketFlags
569 A brief overview on how to use these flags follows.
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.
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.
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
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.
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.
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
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
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.
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.
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().
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.
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().
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
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.
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.
702 wxSocketBase is the base class for all socket-related objects, and it
703 defines all basic IO functionality.
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.
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.
719 @see wxSocketEvent, wxSocketClient, wxSocketServer, @sample{sockets},
720 @ref wxSocketFlags, ::wxSocketEventFlags, ::wxSocketError
722 class wxSocketBase
: public wxObject
727 @name Construction and Destruction
734 Don't use it directly; instead, use wxSocketClient to construct a socket client,
735 or wxSocketServer to construct a socket server.
742 Do not destroy a socket using the delete operator directly;
743 use Destroy() instead. Also, do not create socket objects in the stack.
745 virtual ~wxSocketBase();
748 Destroys the socket safely.
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.
756 Destroy() calls Close() automatically.
758 @return Always @true.
763 Perform the initialization needed in order to use the sockets.
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
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
776 This function should only be called from the main thread.
779 @true if the sockets can be used, @false if the initialization
780 failed and sockets are not available at all.
782 static bool Initialize();
785 Shut down the sockets.
787 This function undoes the call to Initialize() and must be called after
788 every successful call to Initialize().
790 This function should only be called from the main thread, just as
793 static void Shutdown();
804 Returns @true if an error occurred in the last IO operation.
806 Use this function to check for an error condition after one of the
807 following calls: Discard(), Peek(), Read(), ReadMsg(), Unread(), Write(), WriteMsg().
812 Return the local address of the socket.
814 @return @true if no error happened, @false otherwise.
816 virtual bool GetLocal(wxSockAddress
& addr
) const;
819 Return the peer address field of the socket.
821 @return @true if no error happened, @false otherwise.
823 virtual bool GetPeer(wxSockAddress
& addr
) const;
826 Return the socket timeout in seconds.
828 The timeout can be set using SetTimeout() and is 10 minutes by default.
830 long GetTimeout() const;
833 Returns @true if the socket is connected.
835 bool IsConnected() const;
838 Check if the socket can be currently read or written.
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).
848 Returns @true if the socket is not connected.
850 bool IsDisconnected() const;
853 Returns @true if the socket is initialized and ready and @false in other
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.
865 Returns the number of bytes read or written by the last IO call.
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().
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().
877 wxUint32
LastCount() const;
880 Returns the number of bytes read by the last Read() or ReadMsg()
881 call (receive direction only).
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.
887 Unlike LastCount(), the functions Discard(), Peek(), and Unread()
888 are currently not supported by LastReadCount().
892 wxUint32
LastReadCount() const;
895 Returns the number of bytes written by the last Write() or WriteMsg()
896 call (transmit direction only).
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.
904 wxUint32
LastWriteCount() const;
907 Returns the last wxSocket error. See @ref wxSocketError .
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.
916 wxSocketError
LastError() const;
919 Restore the previous state of the socket, as saved with SaveState().
921 Calls to SaveState() and RestoreState() can be nested.
928 Save the current state of the socket in a stack.
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.
944 See also: wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
949 Shut down the socket, disabling further transmission and reception of
950 data and disable events for the socket and frees the associated system
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.
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().
963 virtual bool Close();
966 Shuts down the writing end of the socket.
968 This function simply calls the standard shutdown() function on the
969 underlying socket, indicating that nothing will be written to this
972 void ShutdownOutput();
975 Delete all bytes in the incoming queue.
977 This function always returns immediately and its operation is not
978 affected by IO flags.
980 Use LastCount() to verify the number of bytes actually discarded.
982 If you use Error(), it will always return @false.
984 wxSocketBase
& Discard();
987 Returns current IO flags, as set with SetFlags()
989 wxSocketFlags
GetFlags() const;
992 Use this function to interrupt any wait operation currently in progress.
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.
1001 @see Wait(), WaitForLost(), WaitForRead(), WaitForWrite(),
1002 wxSocketServer::WaitForAccept(), wxSocketClient::WaitOnConnect()
1004 void InterruptWait();
1007 Peek into the socket by copying the next bytes which would be read by
1008 Read() into the provided buffer.
1010 Peeking a buffer doesn't delete it from the socket input queue, i.e.
1011 calling Read() will return the same data.
1013 Use LastCount() to verify the number of bytes actually peeked.
1015 Use Error() to determine if the operation succeeded.
1018 Buffer where to put peeked data.
1022 @return Returns a reference to the current object.
1025 The exact behaviour of Peek() depends on the combination of flags being used.
1026 For a detailed explanation, see SetFlags()
1028 @see Error(), LastError(), LastCount(), SetFlags()
1030 wxSocketBase
& Peek(void* buffer
, wxUint32 nbytes
);
1033 Read up to the given number of bytes from the socket.
1035 Use LastReadCount() to verify the number of bytes actually read.
1036 Use Error() to determine if the operation succeeded.
1039 Buffer where to put read data.
1043 @return Returns a reference to the current object.
1046 The exact behaviour of Read() depends on the combination of flags being used.
1047 For a detailed explanation, see SetFlags()
1049 @see Error(), LastError(), LastReadCount(),
1052 wxSocketBase
& Read(void* buffer
, wxUint32 nbytes
);
1055 Receive a message sent by WriteMsg().
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.
1061 Use LastReadCount() to verify the number of bytes actually read.
1063 Use Error() to determine if the operation succeeded.
1066 Buffer where to put read data.
1070 @return Returns a reference to the current object.
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.
1085 @see Error(), LastError(), LastReadCount(), SetFlags(), WriteMsg()
1087 wxSocketBase
& ReadMsg(void* buffer
, wxUint32 nbytes
);
1090 Use SetFlags to customize IO operation for this socket.
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.
1097 The following flags can be used:
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
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).
1124 For more information on socket events see @ref wxSocketFlags .
1126 void SetFlags(wxSocketFlags flags
);
1129 Set the local address and port to use.
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
1135 virtual bool SetLocal(const wxIPV4address
& local
);
1138 Set the default socket timeout in seconds.
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.
1144 void SetTimeout(long seconds
);
1147 Put the specified data into the input queue.
1149 The data in the buffer will be returned by the next call to Read().
1151 This function is not affected by wxSocket flags.
1153 If you use LastCount(), it will always return @a nbytes.
1155 If you use Error(), it will always return @false.
1158 Buffer to be unread.
1162 @return Returns a reference to the current object.
1164 @see Error(), LastCount(), LastError()
1166 wxSocketBase
& Unread(const void* buffer
, wxUint32 nbytes
);
1169 Wait for any socket event.
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.
1178 Note that it is recommended to use the individual @b WaitForXXX()
1179 functions to wait for the required condition, instead of this one.
1182 Number of seconds to wait.
1183 If -1, it will wait for the default timeout,
1184 as set with SetTimeout().
1186 Number of milliseconds to wait.
1189 @true when any of the above conditions is satisfied or @false if the
1190 timeout was reached.
1192 @see InterruptWait(), wxSocketServer::WaitForAccept(),
1193 WaitForLost(), WaitForRead(),
1194 WaitForWrite(), wxSocketClient::WaitOnConnect()
1196 bool Wait(long seconds
= -1, long millisecond
= 0);
1199 Wait until the connection is lost.
1201 This may happen if the peer gracefully closes the connection or if the
1205 Number of seconds to wait.
1206 If -1, it will wait for the default timeout,
1207 as set with SetTimeout().
1209 Number of milliseconds to wait.
1211 @return Returns @true if the connection was lost, @false if the timeout
1214 @see InterruptWait(), Wait()
1216 bool WaitForLost(long seconds
= -1, long millisecond
= 0);
1219 Wait until the socket is readable.
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).
1226 Notice that this function should not be called if there is already data
1227 available for reading on the socket.
1230 Number of seconds to wait.
1231 If -1, it will wait for the default timeout,
1232 as set with SetTimeout().
1234 Number of milliseconds to wait.
1236 @return Returns @true if the socket becomes readable, @false on timeout.
1238 @see InterruptWait(), Wait()
1240 bool WaitForRead(long seconds
= -1, long millisecond
= 0);
1243 Wait until the socket becomes writable.
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).
1250 Notice that this function should not be called if the socket is already
1254 Number of seconds to wait.
1255 If -1, it will wait for the default timeout,
1256 as set with SetTimeout().
1258 Number of milliseconds to wait.
1260 @return Returns @true if the socket becomes writable, @false on timeout.
1262 @see InterruptWait(), Wait()
1264 bool WaitForWrite(long seconds
= -1, long millisecond
= 0);
1267 Write up to the given number of bytes to the socket.
1269 Use LastWriteCount() to verify the number of bytes actually written.
1271 Use Error() to determine if the operation succeeded.
1274 Buffer with the data to be sent.
1278 @return Returns a reference to the current object.
1282 The exact behaviour of Write() depends on the combination of flags being used.
1283 For a detailed explanation, see SetFlags().
1285 @see Error(), LastError(), LastWriteCount(), SetFlags()
1287 wxSocketBase
& Write(const void* buffer
, wxUint32 nbytes
);
1290 Sends a buffer which can be read using ReadMsg().
1292 WriteMsg() sends a short header before the data so that ReadMsg()
1293 knows how much data should be actually read.
1295 This function always waits for the entire buffer to be sent, unless an
1298 Use LastWriteCount() to verify the number of bytes actually written.
1300 Use Error() to determine if the operation succeeded.
1303 Buffer with the data to be sent.
1305 Number of bytes to send.
1307 @return Returns a reference to the current object.
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,
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.
1323 @see Error(), LastError(), LastWriteCount(), SetFlags(), ReadMsg()
1326 wxSocketBase
& WriteMsg(const void* buffer
, wxUint32 nbytes
);
1332 @name Handling Socket Events
1337 Returns a pointer of the client data for this socket, as set with
1340 void* GetClientData() const;
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
1349 void Notify(bool notify
);
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.
1356 void SetClientData(void* data
);
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
1365 Specifies the event handler you want to use.
1367 The id of socket event.
1369 @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
1371 void SetEventHandler(wxEvtHandler
& handler
, int id
= -1);
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:
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.
1388 sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
1392 In this example, the user will be notified about incoming socket data and
1393 whenever the connection is closed.
1395 For more information on socket events see @ref wxSocketEventFlags .
1397 void SetNotify(wxSocketEventFlags flags
);
1400 Returns the native socket descriptor.
1402 This is intended to use with rarely used specific platform features
1403 that can only be accessed via the actual socket descriptor.
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.
1409 The socket must be successfully initialized, e.g. connected for client
1410 sockets, before this method can be called.
1412 @return Returns the native socket descriptor.
1416 wxSOCKET_T
GetSocket() const;
1424 @class wxDatagramSocket
1431 class wxDatagramSocket
: public wxSocketBase
1440 Socket flags (See wxSocketBase::SetFlags()).
1442 wxDatagramSocket(const wxSockAddress
& addr
,
1443 wxSocketFlags flags
= wxSOCKET_NONE
);
1446 Destructor. Please see wxSocketBase::Destroy().
1448 virtual ~wxDatagramSocket();
1451 Write a buffer of @a nbytes bytes to the socket.
1453 Use wxSocketBase::LastWriteCount() to verify the number of bytes actually wrote.
1454 Use wxSocketBase::Error() to determine if the operation succeeded.
1457 The address of the destination peer for this data.
1459 Buffer where read data is.
1463 @return Returns a reference to the current object.
1465 @see wxSocketBase::LastError(), wxSocketBase::SetFlags()
1467 wxDatagramSocket
& SendTo(const wxSockAddress
& address
,
1468 const void* buffer
, wxUint32 nbytes
);