]>
git.saurik.com Git - wxWidgets.git/blob - interface/socket.h
1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: interface of wxIPV4address
4 // Author: wxWidgets team
6 // Licence: wxWindows license
7 /////////////////////////////////////////////////////////////////////////////
17 class wxIPV4address
: public wxIPaddress
21 Set address to any of the addresses of the current machine. Whenever
22 possible, use this function instead of LocalHost(),
23 as this correctly handles multi-homed hosts and avoids other small
24 problems. Internally, this is the same as setting the IP address
27 @return Returns @true on success, @false if something went wrong.
33 Returns the hostname which matches the IP address.
35 bool Hostname(const wxString
& hostname
);
36 Return value wxString
Hostname();
40 Returns a wxString containing the IP address in dot quad (127.0.0.1) format.
45 Set address to localhost (127.0.0.1). Whenever possible, use the
47 function instead of this one, as this will correctly handle multi-homed
48 hosts and avoid other small problems.
54 Returns the current service.
56 bool Service(const wxString
& service
);
57 Return value
bool Service(unsigned short service
);
58 Return value
unsigned short Service();
72 @see wxSocketServer::WaitForAccept, wxSocketBase::SetNotify,
73 wxSocketBase::Notify, wxSocketServer::AcceptWith
75 class wxSocketServer
: public wxSocketBase
79 Constructs a new server and tries to bind to the specified @e address.
80 Before trying to accept new connections, test whether it succeeded with
81 @ref wxSocketBase::isok wxSocketBase:IsOk.
84 Specifies the local address for the server (e.g. port number).
86 Socket flags (See wxSocketBase::SetFlags)
88 wxSocketServer(const wxSockAddress
& address
,
89 wxSocketFlags flags
= wxSOCKET_NONE
);
92 Destructor (it doesn't close the accepted connections).
97 Accepts an incoming connection request, and creates a new
98 wxSocketBase object which represents
99 the server-side of the connection.
100 If @a wait is @true and there are no pending connections to be
101 accepted, it will wait for the next incoming connection to
102 arrive. @b Warning: This will block the GUI.
103 If @a wait is @false, it will try to accept a pending connection
104 if there is one, but it will always return immediately without blocking
105 the GUI. If you want to use Accept in this way, you can either check for
106 incoming connections with WaitForAccept()
107 or catch @b wxSOCKET_CONNECTION events, then call Accept once you know
108 that there is an incoming connection waiting to be accepted.
110 @return Returns an opened socket connection, or @NULL if an error
111 occurred or if the wait parameter was @false and there
112 were no pending connections.
114 @see WaitForAccept(), wxSocketBase::SetNotify,
115 wxSocketBase::Notify, AcceptWith()
117 wxSocketBase
* Accept(bool wait
= true);
120 Accept an incoming connection using the specified socket object.
123 Socket to be initialized
125 @return Returns @true on success, or @false if an error occurred or if the
126 wait parameter was @false and there were no pending
129 bool AcceptWith(wxSocketBase
& socket
, bool wait
= true);
132 This function waits for an incoming connection. Use it if you want to call
133 Accept() or AcceptWith()
134 with @e wait set to @false, to detect when an incoming connection is waiting
138 Number of seconds to wait.
139 If -1, it will wait for the default timeout,
140 as set with SetTimeout.
142 Number of milliseconds to wait.
144 @return Returns @true if an incoming connection arrived, @false if the
147 bool WaitForAccept(long seconds
= -1, long millisecond
= 0);
156 wxIPaddress is an abstract base class for all internet protocol address
157 objects. Currently, only wxIPV4address
158 is implemented. An experimental implementation for IPV6, wxIPV6address,
164 class wxIPaddress
: public wxSockAddress
168 Internally, this is the same as setting the IP address
170 On IPV4 implementations, 0.0.0.0
171 On IPV6 implementations, ::
173 @return Returns @true on success, @false if something went wrong.
175 virtual bool AnyAddress();
178 Internally, this is the same as setting the IP address
179 to @b INADDR_BROADCAST.
180 On IPV4 implementations, 255.255.255.255
182 @return Returns @true on success, @false if something went wrong.
184 virtual bool BroadcastAddress();
188 Returns the hostname which matches the IP address.
190 virtual bool Hostname(const wxString
& hostname
);
191 Return value
virtual wxString
Hostname();
195 Returns a wxString containing the IP address.
197 virtual wxString
IPAddress();
200 Determines if current address is set to localhost.
202 virtual bool IsLocalHost();
205 Set address to localhost.
206 On IPV4 implementations, 127.0.0.1
207 On IPV6 implementations, ::1
209 @return Returns @true on success, @false if something went wrong.
211 virtual bool LocalHost();
215 Returns the current service.
217 virtual bool Service(const wxString
& service
);
218 Return value
virtual bool Service(unsigned short service
);
219 Return value
virtual unsigned short Service();
226 @class wxSocketClient
233 @see wxSocketClient::WaitOnConnect, wxSocketBase::SetNotify,
236 class wxSocketClient
: public wxSocketBase
243 Socket flags (See wxSocketBase::SetFlags)
245 wxSocketClient(wxSocketFlags flags
= wxSOCKET_NONE
);
248 Destructor. Please see wxSocketBase::Destroy.
254 Connects to a server using the specified address.
255 If @a wait is @true, Connect will wait until the connection
256 completes. @b Warning: This will block the GUI.
257 If @a wait is @false, Connect will try to establish the connection and
258 return immediately, without blocking the GUI. When used this way, even if
259 Connect returns @false, the connection request can be completed later.
260 To detect this, use WaitOnConnect(),
261 or catch @b wxSOCKET_CONNECTION events (for successful establishment)
262 and @b wxSOCKET_LOST events (for connection failure).
265 Address of the server.
267 Bind to the specified local address and port before connecting.
268 The local address and port can also be set using SetLocal,
269 and then using the 2-parameter Connect method.
271 If @true, waits for the connection to complete.
273 @return Returns @true if the connection is established and no error
276 @see WaitOnConnect(), wxSocketBase::SetNotify,
279 bool Connect(wxSockAddress
& address
, bool wait
= true);
280 bool Connect(wxSockAddress
& address
, wxSockAddress
& local
,
285 Wait until a connection request completes, or until the specified timeout
286 elapses. Use this function after issuing a call
287 to Connect() with @e wait set to @false.
290 Number of seconds to wait.
291 If -1, it will wait for the default timeout,
292 as set with SetTimeout.
294 Number of milliseconds to wait.
296 @return WaitOnConnect returns @true if the connection request completes.
297 This does not necessarily mean that the connection was
298 successfully established; it might also happen that the
299 connection was refused by the peer. Use IsConnected to
300 distinguish between these two situations.
302 bool WaitOnConnect(long seconds
= -1, long milliseconds
= 0);
311 You are unlikely to need to use this class: only wxSocketBase uses it.
316 @see wxSocketBase, wxIPaddress, wxIPV4address
318 class wxSockAddress
: public wxObject
332 Delete all informations about the address.
337 Returns the length of the socket address.
348 This event class contains information about socket events.
353 @see wxSocketBase, wxSocketClient, wxSocketServer
355 class wxSocketEvent
: public wxEvent
361 wxSocketEvent(int id
= 0);
364 Gets the client data of the socket which generated this event, as
365 set with wxSocketBase::SetClientData.
367 void* GetClientData();
370 Returns the socket object to which this event refers to. This makes
371 it possible to use the same event handler for different sockets.
373 wxSocketBase
* GetSocket() const;
376 Returns the socket event type.
378 wxSocketNotify
GetSocketEvent() const;
387 wxSocketBase is the base class for all socket-related objects, and it
388 defines all basic IO functionality.
390 Note: (Workaround for implementation limitation for wxWidgets up to 2.5.x)
391 If you want to use sockets or derived classes such as wxFTP in a secondary
393 call wxSocketBase::Initialize() (undocumented) from the main thread before
395 any sockets - in wxApp::OnInit for example.
396 See http://wiki.wxwidgets.org/wiki.pl?WxSocket or
397 http://www.litwindow.com/knowhow/knowhow.html for more details.
402 @see wxSocketEvent, wxSocketClient, wxSocketServer, @ref overview_samplesockets
405 class wxSocketBase
: public wxObject
409 Default constructor. Don't use it directly; instead, use
410 wxSocketClient to construct a socket client, or
411 wxSocketServer to construct a socket server.
416 Destructor. Do not destroy a socket using the delete operator directly;
417 use Destroy() instead. Also, do not create
418 socket objects in the stack.
423 Functions that perform basic IO functionality.
439 Functions that perform a timed wait on a certain IO condition.
451 wxSocketServer::WaitForAccept
453 wxSocketClient::WaitOnConnect
454 Functions that allow applications to customize socket IO as needed.
466 This function shuts down the socket, disabling further transmission and
467 reception of data; it also disables events for the socket and frees the
468 associated system resources. Upon socket destruction, Close is automatically
469 called, so in most cases you won't need to do it yourself, unless you
470 explicitly want to shut down the socket, typically to notify the peer
471 that you are closing the connection.
476 @ref construct() wxSocketBase
478 @ref destruct() ~wxSocketBase
485 Destroys the socket safely. Use this function instead of the delete operator,
486 since otherwise socket events could reach the application even after the
487 socket has been destroyed. To prevent this problem, this function appends
488 the wxSocket to a list of object to be deleted on idle time, after all
489 events have been processed. For the same reason, you should avoid creating
490 socket objects in the stack.
491 Destroy calls Close() automatically.
493 @return Always @true.
498 This function simply deletes all bytes in the incoming queue. This function
499 always returns immediately and its operation is not affected by IO flags.
500 Use LastCount() to verify the number of bytes actually discarded.
501 If you use Error(), it will always return @false.
503 wxSocketBase
Discard();
506 Returns @true if an error occurred in the last IO operation.
507 Use this function to check for an error condition after one of the
508 following calls: Discard, Peek, Read, ReadMsg, Unread, Write, WriteMsg.
513 Returns a pointer of the client data for this socket, as set with
516 void* GetClientData() const;
519 Returns current IO flags, as set with SetFlags()
521 wxSocketFlags
GetFlags() const;
524 This function returns the local address field of the socket. The local
525 address field contains the complete local address of the socket (local
526 address, local port, ...).
528 @return @true if no error happened, @false otherwise.
530 bool GetLocal(wxSockAddress
& addr
) const;
533 This function returns the peer address field of the socket. The peer
534 address field contains the complete peer host address of the socket
535 (address, port, ...).
537 @return @true if no error happened, @false otherwise.
539 bool GetPeer(wxSockAddress
& addr
) const;
542 Functions that allow applications to receive socket events.
556 Use this function to interrupt any wait operation currently in progress.
557 Note that this is not intended as a regular way to interrupt a Wait call,
558 but only as an escape mechanism for exceptional situations where it is
559 absolutely necessary to use it, for example to abort an operation due to
560 some exception or abnormal problem. InterruptWait is automatically called
561 when you Close() a socket (and thus also upon
562 socket destruction), so you don't need to use it in these cases.
564 wxSocketServer::WaitForAccept,
568 wxSocketClient::WaitOnConnect
570 void InterruptWait();
573 Returns @true if the socket is connected.
575 bool IsConnected() const;
578 This function waits until the socket is readable. This might mean that
579 queued data is available for reading or, for streamed sockets, that
580 the connection has been closed, so that a read operation will complete
581 immediately without blocking (unless the @b wxSOCKET_WAITALL flag
582 is set, in which case the operation might still block).
587 Returns @true if the socket is not connected.
589 bool IsDisconnected() const;
592 Returns @true if the socket is initialized and ready and @false in other
598 Returns the number of bytes read or written by the last IO call.
599 Use this function to get the number of bytes actually transferred
600 after using one of the following IO calls: Discard, Peek, Read,
601 ReadMsg, Unread, Write, WriteMsg.
603 wxUint32
LastCount() const;
606 Returns the last wxSocket error. See @ref overview_wxsocketbase "wxSocket
608 Please note that this function merely returns the last error code,
609 but it should not be used to determine if an error has occurred (this
610 is because successful operations do not change the LastError value).
611 Use Error() first, in order to determine
612 if the last IO call failed. If this returns @true, use LastError
613 to discover the cause of the error.
615 wxSocketError
LastError() const;
618 According to the @a notify value, this function enables
619 or disables socket events. If @a notify is @true, the events
620 configured with SetNotify() will
621 be sent to the application. If @a notify is @false; no events
624 void Notify(bool notify
);
627 This function peeks a buffer of @a nbytes bytes from the socket.
628 Peeking a buffer doesn't delete it from the socket input queue.
629 Use LastCount() to verify the number of bytes actually peeked.
630 Use Error() to determine if the operation succeeded.
633 Buffer where to put peeked data.
637 @return Returns a reference to the current object.
639 @see Error(), LastError(), LastCount(),
642 wxSocketBase
Peek(void* buffer
, wxUint32 nbytes
);
645 This function reads a buffer of @a nbytes bytes from the socket.
646 Use LastCount() to verify the number of bytes actually read.
647 Use Error() to determine if the operation succeeded.
650 Buffer where to put read data.
654 @return Returns a reference to the current object.
656 @see Error(), LastError(), LastCount(),
659 wxSocketBase
Read(void* buffer
, wxUint32 nbytes
);
662 This function reads a buffer sent by WriteMsg()
663 on a socket. If the buffer passed to the function isn't big enough, the
664 remaining bytes will be discarded. This function always waits for the
665 buffer to be entirely filled, unless an error occurs.
666 Use LastCount() to verify the number of bytes actually read.
667 Use Error() to determine if the operation succeeded.
670 Buffer where to put read data.
674 @return Returns a reference to the current object.
676 @see Error(), LastError(), LastCount(),
677 SetFlags(), WriteMsg()
679 wxSocketBase
ReadMsg(void* buffer
, wxUint32 nbytes
);
682 This function restores the previous state of the socket, as saved
684 Calls to SaveState and RestoreState can be nested.
691 This function saves the current state of the socket in a stack. Socket
692 state includes flags, as set with SetFlags(),
693 event mask, as set with SetNotify() and
694 Notify(), user data, as set with
696 Calls to SaveState and RestoreState can be nested.
703 Sets user-supplied client data for this socket. All socket events will
704 contain a pointer to this data, which can be retrieved with
705 the wxSocketEvent::GetClientData function.
707 void SetClientData(void* data
);
710 Sets an event handler to be called when a socket event occurs. The
711 handler will be called for those events for which notification is
712 enabled with SetNotify() and
716 Specifies the event handler you want to use.
718 The id of socket event.
720 @see SetNotify(), Notify(), wxSocketEvent, wxEvtHandler
722 void SetEventHandler(wxEvtHandler
& handler
, int id
= -1);
725 Use SetFlags to customize IO operation for this socket.
726 The @a flags parameter may be a combination of flags ORed together.
727 The following flags can be used:
731 Normal functionality.
735 Read/write as much data as possible and return immediately.
739 Wait for all required data to be read/written unless an error occurs.
743 Block the GUI (do not yield) while reading/writing data.
745 @b wxSOCKET_REUSEADDR
747 Allows the use of an in-use port (wxServerSocket only)
749 @b wxSOCKET_BROADCAST
751 Switches the socket to broadcast mode
755 Stops the socket from being bound to a specific adapter (normally used in
756 conjunction with @b wxSOCKET_BROADCAST)
758 A brief overview on how to use these flags follows.
759 If no flag is specified (this is the same as @b wxSOCKET_NONE),
760 IO calls will return after some data has been read or written, even
761 when the transfer might not be complete. This is the same as issuing
762 exactly one blocking low-level call to recv() or send(). Note
763 that @e blocking here refers to when the function returns, not
764 to whether the GUI blocks during this time.
765 If @b wxSOCKET_NOWAIT is specified, IO calls will return immediately.
766 Read operations will retrieve only available data. Write operations will
767 write as much data as possible, depending on how much space is available
768 in the output buffer. This is the same as issuing exactly one nonblocking
769 low-level call to recv() or send(). Note that @e nonblocking here
770 refers to when the function returns, not to whether the GUI blocks during
772 If @b wxSOCKET_WAITALL is specified, IO calls won't return until ALL
773 the data has been read or written (or until an error occurs), blocking if
774 necessary, and issuing several low level calls if necessary. This is the
775 same as having a loop which makes as many blocking low-level calls to
776 recv() or send() as needed so as to transfer all the data. Note
777 that @e blocking here refers to when the function returns, not
778 to whether the GUI blocks during this time.
779 The @b wxSOCKET_BLOCK flag controls whether the GUI blocks during
780 IO operations. If this flag is specified, the socket will not yield
781 during IO calls, so the GUI will remain blocked until the operation
782 completes. If it is not used, then the application must take extra
783 care to avoid unwanted reentrance.
784 The @b wxSOCKET_REUSEADDR flag controls the use of the SO_REUSEADDR standard
785 setsockopt() flag. This flag allows the socket to bind to a port that is
787 This is mostly used on UNIX-based systems to allow rapid starting and stopping
789 otherwise you may have to wait several minutes for the port to become available.
790 wxSOCKET_REUSEADDR can also be used with socket clients to (re)bind to a
791 particular local port
792 for an outgoing connection.
793 This option can have surprising platform dependent behavior, so check the
795 your platform's implementation of setsockopt(). Note that on BSD-based systems
797 use of wxSOCKET_REUSEADDR implies SO_REUSEPORT in addition to SO_REUSEADDR to
800 The @b wxSOCKET_BROADCAST flag controls the use of the SO_BROADCAST standard
801 setsockopt() flag. This flag allows the socket to use the broadcast address,
803 used in conjunction with @b wxSOCKET_NOBIND and wxIPaddress::BroadcastAddress.
805 @b wxSOCKET_NONE will try to read at least SOME data, no matter how much.
806 @b wxSOCKET_NOWAIT will always return immediately, even if it cannot
807 read or write ANY data.
808 @b wxSOCKET_WAITALL will only return when it has read or written ALL
810 @b wxSOCKET_BLOCK has nothing to do with the previous flags and
811 it controls whether the GUI blocks.
812 @b wxSOCKET_REUSEADDR controls special platform-specific behavior for
813 reusing local addresses/ports.
815 void SetFlags(wxSocketFlags flags
);
818 This function allows you to set the local address and port,
819 useful when an application needs to reuse a particular port. When
820 a local port is set for a wxSocketClient,
821 @b bind will be called before @b connect.
823 bool SetLocal(wxIPV4address
& local
);
826 SetNotify specifies which socket events are to be sent to the event handler.
827 The @a flags parameter may be combination of flags ORed together. The
828 following flags can be used:
830 @b wxSOCKET_INPUT_FLAG
832 to receive wxSOCKET_INPUT
834 @b wxSOCKET_OUTPUT_FLAG
836 to receive wxSOCKET_OUTPUT
838 @b wxSOCKET_CONNECTION_FLAG
840 to receive wxSOCKET_CONNECTION
842 @b wxSOCKET_LOST_FLAG
844 to receive wxSOCKET_LOST
848 In this example, the user will be notified about incoming socket data and
849 whenever the connection is closed.
850 For more information on socket events see @ref overview_wxsocketbase "wxSocket
853 void SetNotify(wxSocketEventFlags flags
);
856 This function sets the default socket timeout in seconds. This timeout
857 applies to all IO calls, and also to the Wait() family
858 of functions if you don't specify a wait interval. Initially, the default
859 timeout is 10 minutes.
861 void SetTimeout(int seconds
);
864 Functions to retrieve current state and miscellaneous info.
889 This function unreads a buffer. That is, the data in the buffer is put back
890 in the incoming queue. This function is not affected by wxSocket flags.
891 If you use LastCount(), it will always return @e nbytes.
892 If you use Error(), it will always return @false.
899 @return Returns a reference to the current object.
901 @see Error(), LastCount(), LastError()
903 wxSocketBase
Unread(const void* buffer
, wxUint32 nbytes
);
906 This function waits until any of the following conditions is @true:
908 The socket becomes readable.
909 The socket becomes writable.
910 An ongoing connection request has completed (wxSocketClient only)
911 An incoming connection request has arrived (wxSocketServer only)
912 The connection has been closed.
913 Note that it is recommended to use the individual Wait functions
914 to wait for the required condition, instead of this one.
917 Number of seconds to wait.
918 If -1, it will wait for the default timeout,
919 as set with SetTimeout.
921 Number of milliseconds to wait.
923 @return Returns @true when any of the above conditions is satisfied,
924 @false if the timeout was reached.
926 @see InterruptWait(), wxSocketServer::WaitForAccept,
927 WaitForLost(), WaitForRead(),
928 WaitForWrite(), wxSocketClient::WaitOnConnect
930 bool Wait(long seconds
= -1, long millisecond
= 0);
933 This function waits until the connection is lost. This may happen if
934 the peer gracefully closes the connection or if the connection breaks.
937 Number of seconds to wait.
938 If -1, it will wait for the default timeout,
939 as set with SetTimeout.
941 Number of milliseconds to wait.
943 @return Returns @true if the connection was lost, @false if the timeout
946 @see InterruptWait(), Wait()
948 bool WaitForLost(long seconds
= -1, long millisecond
= 0);
951 This function waits until the socket is readable. This might mean that
952 queued data is available for reading or, for streamed sockets, that
953 the connection has been closed, so that a read operation will complete
954 immediately without blocking (unless the @b wxSOCKET_WAITALL flag
955 is set, in which case the operation might still block).
958 Number of seconds to wait.
959 If -1, it will wait for the default timeout,
960 as set with SetTimeout.
962 Number of milliseconds to wait.
964 @return Returns @true if the socket becomes readable, @false on timeout.
966 @see InterruptWait(), Wait()
968 bool WaitForRead(long seconds
= -1, long millisecond
= 0);
971 This function waits until the socket becomes writable. This might mean that
972 the socket is ready to send new data, or for streamed sockets, that the
973 connection has been closed, so that a write operation is guaranteed to
974 complete immediately (unless the @b wxSOCKET_WAITALL flag is set,
975 in which case the operation might still block).
978 Number of seconds to wait.
979 If -1, it will wait for the default timeout,
980 as set with SetTimeout.
982 Number of milliseconds to wait.
984 @return Returns @true if the socket becomes writable, @false on timeout.
986 @see InterruptWait(), Wait()
988 bool WaitForWrite(long seconds
= -1, long millisecond
= 0);
991 This function writes a buffer of @a nbytes bytes to the socket.
992 Use LastCount() to verify the number of bytes actually written.
993 Use Error() to determine if the operation succeeded.
996 Buffer with the data to be sent.
1000 @return Returns a reference to the current object.
1002 @see Error(), LastError(), LastCount(),
1005 wxSocketBase
Write(const void* buffer
, wxUint32 nbytes
);
1008 This function writes a buffer of @a nbytes bytes from the socket, but it
1009 writes a short header before so that ReadMsg()
1010 knows how much data should it actually read. So, a buffer sent with WriteMsg
1011 @b must be read with ReadMsg. This function always waits for the entire
1012 buffer to be sent, unless an error occurs.
1013 Use LastCount() to verify the number of bytes actually written.
1014 Use Error() to determine if the operation succeeded.
1017 Buffer with the data to be sent.
1019 Number of bytes to send.
1021 @return Returns a reference to the current object.
1023 wxSocketBase
WriteMsg(const void* buffer
, wxUint32 nbytes
);
1029 @class wxDatagramSocket
1036 @see wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount,
1037 wxSocketBase::SetFlags,
1039 class wxDatagramSocket
: public wxSocketBase
1046 Socket flags (See wxSocketBase::SetFlags)
1048 wxDatagramSocket(wxSocketFlags flags
= wxSOCKET_NONE
);
1051 Destructor. Please see wxSocketBase::Destroy.
1053 ~wxDatagramSocket();
1056 This function reads a buffer of @a nbytes bytes from the socket.
1057 Use wxSocketBase::LastCount to verify the number of bytes actually read.
1058 Use wxSocketBase::Error to determine if the operation succeeded.
1061 Any address - will be overwritten with the address of the peer that sent
1064 Buffer where to put read data.
1068 @return Returns a reference to the current object, and the address of
1069 the peer that sent the data on address param.
1071 @see wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount,
1072 wxSocketBase::SetFlags,
1074 wxDatagramSocket
ReceiveFrom(wxSockAddress
& address
,
1079 This function writes a buffer of @a nbytes bytes to the socket.
1080 Use wxSocketBase::LastCount to verify the number of bytes actually wrote.
1081 Use wxSocketBase::Error to determine if the operation succeeded.
1084 The address of the destination peer for this data.
1086 Buffer where read data is.
1090 @return Returns a reference to the current object.
1092 wxDatagramSocket
SendTo(const wxSockAddress
& address
,