Contents Up Previous Next

wxSocketBase

wxSocketBase is the base class for all socket-related objects, and it defines all basic IO functionality.

Note: (Workaround for implementation limitation for wxWidgets up to 2.5.x) If you want to use sockets or derived classes such as wxFTP in a secondary thread, call wxSocketBase::Initialize() (undocumented) from the main thread before creating any sockets - in wxApp::OnInit for example. See http://wiki.wxwidgets.org/wiki.pl?WxSocket or http://www.litwindow.com/knowhow/knowhow.html for more details.

Derived from

wxObject

Include files

<wx/socket.h>

wxSocket errors

wxSOCKET_NOERROR No error happened.
wxSOCKET_INVOP Invalid operation.
wxSOCKET_IOERR Input/Output error.
wxSOCKET_INVADDR Invalid address passed to wxSocket.
wxSOCKET_INVSOCK Invalid socket (uninitialized).
wxSOCKET_NOHOST No corresponding host.
wxSOCKET_INVPORT Invalid port.
wxSOCKET_WOULDBLOCK The socket is non-blocking and the operation would block.
wxSOCKET_TIMEDOUT The timeout for this operation expired.
wxSOCKET_MEMERR Memory exhausted.

wxSocket events

wxSOCKET_INPUT There is data available for reading.
wxSOCKET_OUTPUT The socket is ready to be written to.
wxSOCKET_CONNECTION Incoming connection request (server), or successful connection establishment (client).
wxSOCKET_LOST The connection has been closed.

A brief note on how to use these events:

The wxSOCKET_INPUT event will be issued whenever there is data available for reading. This will be the case if the input queue was empty and new data arrives, or if the application has read some data yet there is still more data available. This means that the application does not need to read all available data in response to a wxSOCKET_INPUT event, as more events will be produced as necessary.

The wxSOCKET_OUTPUT event is issued when a socket is first connected with Connect or accepted with Accept. After that, new events will be generated only after an output operation fails with wxSOCKET_WOULDBLOCK and buffer space becomes available again. This means that the application should assume that it can write data to the socket until an wxSOCKET_WOULDBLOCK error occurs; after this, whenever the socket becomes writable again the application will be notified with another wxSOCKET_OUTPUT event.

The wxSOCKET_CONNECTION event is issued when a delayed connection request completes successfully (client) or when a new connection arrives at the incoming queue (server).

The wxSOCKET_LOST event is issued when a close indication is received for the socket. This means that the connection broke down or that it was closed by the peer. Also, this event will be issued if a connection request fails.

Event handling

To process events coming from a socket object, use the following event handler macro to direct events to member functions that take a wxSocketEvent argument.

EVT_SOCKET(id, func) Process a wxEVT_SOCKET event.

See also

wxSocketEvent, wxSocketClient, wxSocketServer, Sockets sample

Function groups

Construction and destruction
Socket state
Basic IO
Handling socket events
wxSocketBase::wxSocketBase
wxSocketBase::~wxSocketBase
wxSocketBase::Callback
wxSocketBase::CallbackData
wxSocketBase::Close
wxSocketBase::Destroy
wxSocketBase::Discard
wxSocketBase::Error
wxSocketBase::GetClientData
wxSocketBase::GetLocal
wxSocketBase::GetFlags
wxSocketBase::GetPeer
wxSocketBase::InterruptWait
wxSocketBase::IsConnected
wxSocketBase::IsData
wxSocketBase::IsDisconnected
wxSocketBase::LastCount
wxSocketBase::LastError
wxSocketBase::Notify
wxSocketBase::Ok
wxSocketBase::RestoreState
wxSocketBase::SaveState
wxSocketBase::SetClientData
wxSocketBase::SetEventHandler
wxSocketBase::SetFlags
wxSocketBase::SetNotify
wxSocketBase::SetTimeout
wxSocketBase::Peek
wxSocketBase::Read
wxSocketBase::ReadMsg
wxSocketBase::Unread
wxSocketBase::Wait
wxSocketBase::WaitForLost
wxSocketBase::WaitForRead
wxSocketBase::WaitForWrite
wxSocketBase::Write
wxSocketBase::WriteMsg


Construction and destruction

wxSocketBase
~wxSocketBase
Destroy


Socket state

Functions to retrieve current state and miscellaneous info.

Error
GetLocal
GetPeer IsConnected
IsData
IsDisconnected
LastCount
LastError
Ok
SaveState
RestoreState


Basic IO

Functions that perform basic IO functionality.

Close
Discard
Peek
Read
ReadMsg
Unread
Write
WriteMsg

Functions that perform a timed wait on a certain IO condition.

InterruptWait
Wait
WaitForLost
WaitForRead
WaitForWrite

and also:

wxSocketServer::WaitForAccept
wxSocketClient::WaitOnConnect

Functions that allow applications to customize socket IO as needed.

GetFlags
SetFlags
SetTimeout


Handling socket events

Functions that allow applications to receive socket events.

Notify
SetNotify
GetClientData
SetClientData
SetEventHandler

Callback functions are also available, but they are provided for backwards compatibility only. Their use is strongly discouraged in favour of events, and should be considered deprecated. Callbacks may be unsupported in future releases of wxWidgets.

Callback
CallbackData


wxSocketBase::wxSocketBase

wxSocketBase()

Default constructor. Don't use it directly; instead, use wxSocketClient to construct a socket client, or wxSocketServer to construct a socket server.


wxSocketBase::~wxSocketBase

~wxSocketBase()

Destructor. Do not destroy a socket using the delete operator directly; use Destroy instead. Also, do not create socket objects in the stack.


wxSocketBase::Callback

wxSocketBase::wxSockCbk Callback(wxSocketBase::wxSockCbk callback)

You can setup a callback function to be called when an event occurs. The function will be called only for those events for which notification has been enabled with Notify and SetNotify. The prototype of the callback must be as follows:

void SocketCallback(wxSocketBase& sock, wxSocketNotify evt, char *cdata);
The first parameter is a reference to the socket object in which the event occurred. The second parameter tells you which event occurred. (See wxSocket events). The third parameter is the user data you specified using CallbackData.

Return value

A pointer to the previous callback.

Remark/Warning

Note that callbacks are now deprecated and unsupported, and they remain for backwards compatibility only. Use events instead.

See also

wxSocketBase::CallbackData, wxSocketBase::SetNotify, wxSocketBase::Notify


wxSocketBase::CallbackData

char * CallbackData(char *cdata)

This function sets the the user data which will be passed to a callback function set via Callback.

Return value

A pointer to the previous user data.

Remark/Warning

Note that callbacks are now deprecated and unsupported, and they remain for backwards compatibility only. Use events instead.

See also

wxSocketBase::Callback, wxSocketBase::SetNotify, wxSocketBase::Notify


wxSocketBase::Close

void Close()

This function shuts down the socket, disabling further transmission and reception of data; it also disables events for the socket and frees the associated system resources. Upon socket destruction, Close is automatically called, so in most cases you won't need to do it yourself, unless you explicitly want to shut down the socket, typically to notify the peer that you are closing the connection.

Remark/Warning

Although Close immediately disables events for the socket, it is possible that event messages may be waiting in the application's event queue. The application must therefore be prepared to handle socket event messages even after calling Close.


wxSocketBase::Destroy

bool Destroy()

Destroys the socket safely. Use this function instead of the delete operator, since otherwise socket events could reach the application even after the socket has been destroyed. To prevent this problem, this function appends the wxSocket to a list of object to be deleted on idle time, after all events have been processed. For the same reason, you should avoid creating socket objects in the stack.

Destroy calls Close automatically.

Return value

Always true.


wxSocketBase::Discard

wxSocketBase& Discard()

This function simply deletes all bytes in the incoming queue. This function always returns immediately and its operation is not affected by IO flags.

Use LastCount to verify the number of bytes actually discarded.

If you use Error, it will always return false.


wxSocketBase::Error

bool Error() const

Returns true if an error occurred in the last IO operation.

Use this function to check for an error condition after one of the following calls: Discard, Peek, Read, ReadMsg, Unread, Write, WriteMsg.


wxSocketBase::GetClientData

void * GetClientData() const

Returns a pointer of the client data for this socket, as set with SetClientData


wxSocketBase::GetLocal

bool GetLocal(wxSockAddress& addr) const

This function returns the local address field of the socket. The local address field contains the complete local address of the socket (local address, local port, ...).

Return value

true if no error happened, false otherwise.


wxSocketBase::GetFlags

wxSocketFlags GetFlags() const

Returns current IO flags, as set with SetFlags


wxSocketBase::GetPeer

bool GetPeer(wxSockAddress& addr) const

This function returns the peer address field of the socket. The peer address field contains the complete peer host address of the socket (address, port, ...).

Return value

true if no error happened, false otherwise.


wxSocketBase::InterruptWait

void InterruptWait()

Use this function to interrupt any wait operation currently in progress. Note that this is not intended as a regular way to interrupt a Wait call, but only as an escape mechanism for exceptional situations where it is absolutely necessary to use it, for example to abort an operation due to some exception or abnormal problem. InterruptWait is automatically called when you Close a socket (and thus also upon socket destruction), so you don't need to use it in these cases.

wxSocketBase::Wait, wxSocketServer::WaitForAccept, wxSocketBase::WaitForLost, wxSocketBase::WaitForRead, wxSocketBase::WaitForWrite, wxSocketClient::WaitOnConnect


wxSocketBase::IsConnected

bool IsConnected() const

Returns true if the socket is connected.


wxSocketBase::IsData

bool IsData() const

This function waits until the socket is readable. This might mean that queued data is available for reading or, for streamed sockets, that the connection has been closed, so that a read operation will complete immediately without blocking (unless the wxSOCKET_WAITALL flag is set, in which case the operation might still block).


wxSocketBase::IsDisconnected

bool IsDisconnected() const

Returns true if the socket is not connected.


wxSocketBase::LastCount

wxUint32 LastCount() const

Returns the number of bytes read or written by the last IO call.

Use this function to get the number of bytes actually transferred after using one of the following IO calls: Discard, Peek, Read, ReadMsg, Unread, Write, WriteMsg.


wxSocketBase::LastError

wxSocketError LastError() const

Returns the last wxSocket error. See wxSocket errors.

Please note that this function merely returns the last error code, but it should not be used to determine if an error has occurred (this is because successful operations do not change the LastError value). Use Error first, in order to determine if the last IO call failed. If this returns true, use LastError to discover the cause of the error.


wxSocketBase::Notify

void Notify(bool notify)

According to the notify value, this function enables or disables socket events. If notify is true, the events configured with SetNotify will be sent to the application. If notify is false; no events will be sent.


wxSocketBase::Ok

bool Ok() const

Returns true if the socket is initialized and ready and false in other cases.

Remark/Warning

For wxSocketClient, Ok won't return true unless the client is connected to a server.

For wxSocketServer, Ok will return true if the server could bind to the specified address and is already listening for new connections.

Ok does not check for IO errors; use Error instead for that purpose.


wxSocketBase::RestoreState

void RestoreState()

This function restores the previous state of the socket, as saved with SaveState

Calls to SaveState and RestoreState can be nested.

See also

wxSocketBase::SaveState


wxSocketBase::SaveState

void SaveState()

This function saves the current state of the socket in a stack. Socket state includes flags, as set with SetFlags, event mask, as set with SetNotify and Notify, user data, as set with SetClientData, and asynchronous callback settings, as set with Callback and CallbackData.

Calls to SaveState and RestoreState can be nested.

See also

wxSocketBase::RestoreState


wxSocketBase::SetClientData

void SetClientData(void *data)

Sets user-supplied client data for this socket. All socket events will contain a pointer to this data, which can be retrieved with the wxSocketEvent::GetClientData function.


wxSocketBase::SetEventHandler

void SetEventHandler(wxEvtHandler& handler, int id = -1)

Sets an event handler to be called when a socket event occurs. The handler will be called for those events for which notification is enabled with SetNotify and Notify.

Parameters

handler

id

See also

wxSocketBase::SetNotify, wxSocketBase::Notify, wxSocketEvent, wxEvtHandler


wxSocketBase::SetFlags

void SetFlags(wxSocketFlags flags)

Use SetFlags to customize IO operation for this socket. The flags parameter may be a combination of flags ORed together. The following flags can be used:

wxSOCKET_NONE Normal functionality.
wxSOCKET_NOWAIT Read/write as much data as possible and return immediately.
wxSOCKET_WAITALL Wait for all required data to be read/written unless an error occurs.
wxSOCKET_BLOCK Block the GUI (do not yield) while reading/writing data.
wxSOCKET_REUSEADDR Allows the use of an in-use port (wxServerSocket only)

A brief overview on how to use these flags follows.

If no flag is specified (this is the same as wxSOCKET_NONE), IO calls will return after some data has been read or written, even when the transfer might not be complete. This is the same as issuing exactly one blocking low-level call to recv() or send(). Note that blocking here refers to when the function returns, not to whether the GUI blocks during this time.

If wxSOCKET_NOWAIT is specified, IO calls will return immediately. Read operations will retrieve only available data. Write operations will write as much data as possible, depending on how much space is available in the output buffer. This is the same as issuing exactly one nonblocking low-level call to recv() or send(). Note that nonblocking here refers to when the function returns, not to whether the GUI blocks during this time.

If wxSOCKET_WAITALL is specified, IO calls won't return until ALL the data has been read or written (or until an error occurs), blocking if necessary, and issuing several low level calls if necessary. This is the same as having a loop which makes as many blocking low-level calls to recv() or send() as needed so as to transfer all the data. Note that blocking here refers to when the function returns, not to whether the GUI blocks during this time.

The wxSOCKET_BLOCK flag controls whether the GUI blocks during IO operations. If this flag is specified, the socket will not yield during IO calls, so the GUI will remain blocked until the operation completes. If it is not used, then the application must take extra care to avoid unwanted reentrance.

The wxSOCKET_REUSEADDR flag controls the use of the SO_REUSEADDR standard setsockopt() flag. This flag allows the socket to bind to a port that is already in use. This is mostly used on UNIX-based systems to allow rapid starting and stopping of a server - otherwise you may have to wait several minutes for the port to become available. This option can have suprising platform dependent behavior, check the documentation for your platforms implementation of setsockopt().

So:

wxSOCKET_NONE will try to read at least SOME data, no matter how much.

wxSOCKET_NOWAIT will always return immediately, even if it cannot read or write ANY data.

wxSOCKET_WAITALL will only return when it has read or written ALL the data.

wxSOCKET_BLOCK has nothing to do with the previous flags and it controls whether the GUI blocks.

wxSOCKET_REUSEADDR controls special platform-specific behavior for wxServerSocket.


wxSocketBase::SetNotify

void SetNotify(wxSocketEventFlags flags)

SetNotify specifies which socket events are to be sent to the event handler. The flags parameter may be combination of flags ORed together. The following flags can be used:

wxSOCKET_INPUT_FLAG to receive wxSOCKET_INPUT
wxSOCKET_OUTPUT_FLAG to receive wxSOCKET_OUTPUT
wxSOCKET_CONNECTION_FLAG to receive wxSOCKET_CONNECTION
wxSOCKET_LOST_FLAG to receive wxSOCKET_LOST

For example:

  sock.SetNotify(wxSOCKET_INPUT_FLAG | wxSOCKET_LOST_FLAG);
  sock.Notify(true);
In this example, the user will be notified about incoming socket data and whenever the connection is closed.

For more information on socket events see wxSocket events.


wxSocketBase::SetTimeout

void SetTimeout(int seconds)

This function sets the default socket timeout in seconds. This timeout applies to all IO calls, and also to the Wait family of functions if you don't specify a wait interval. Initially, the default timeout is 10 minutes.


wxSocketBase::Peek

wxSocketBase& Peek(void * buffer, wxUint32 nbytes)

This function peeks a buffer of nbytes bytes from the socket. Peeking a buffer doesn't delete it from the socket input queue.

Use LastCount to verify the number of bytes actually peeked.

Use Error to determine if the operation succeeded.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

Remark/Warning

The exact behaviour of wxSocketBase::Peek depends on the combination of flags being used. For a detailed explanation, see wxSocketBase::SetFlags

See also

wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount, wxSocketBase::SetFlags


wxSocketBase::Read

wxSocketBase& Read(void * buffer, wxUint32 nbytes)

This function reads a buffer of nbytes bytes from the socket.

Use LastCount to verify the number of bytes actually read.

Use Error to determine if the operation succeeded.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

Remark/Warning

The exact behaviour of wxSocketBase::Read depends on the combination of flags being used. For a detailed explanation, see wxSocketBase::SetFlags.

See also

wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount, wxSocketBase::SetFlags


wxSocketBase::ReadMsg

wxSocketBase& ReadMsg(void * buffer, wxUint32 nbytes)

This function reads a buffer sent by WriteMsg on a socket. If the buffer passed to the function isn't big enough, the remaining bytes will be discarded. This function always waits for the buffer to be entirely filled, unless an error occurs.

Use LastCount to verify the number of bytes actually read.

Use Error to determine if the operation succeeded.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

Remark/Warning

wxSocketBase::ReadMsg will behave as if the wxSOCKET_WAITALL flag was always set and it will always ignore the wxSOCKET_NOWAIT flag. The exact behaviour of ReadMsg depends on the wxSOCKET_BLOCK flag. For a detailed explanation, see wxSocketBase::SetFlags.

See also

wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount, wxSocketBase::SetFlags, wxSocketBase::WriteMsg


wxSocketBase::Unread

wxSocketBase& Unread(const void * buffer, wxUint32 nbytes)

This function unreads a buffer. That is, the data in the buffer is put back in the incoming queue. This function is not affected by wxSocket flags.

If you use LastCount, it will always return nbytes.

If you use Error, it will always return false.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

See also

wxSocketBase::Error, wxSocketBase::LastCount, wxSocketBase::LastError


wxSocketBase::Wait

bool Wait(long seconds = -1, long millisecond = 0)

This function waits until any of the following conditions is true:

Note that it is recommended to use the individual Wait functions to wait for the required condition, instead of this one.

Parameters

seconds

millisecond

Return value

Returns true when any of the above conditions is satisfied, false if the timeout was reached.

See also

wxSocketBase::InterruptWait, wxSocketServer::WaitForAccept, wxSocketBase::WaitForLost, wxSocketBase::WaitForRead, wxSocketBase::WaitForWrite, wxSocketClient::WaitOnConnect


wxSocketBase::WaitForLost

bool Wait(long seconds = -1, long millisecond = 0)

This function waits until the connection is lost. This may happen if the peer gracefully closes the connection or if the connection breaks.

Parameters

seconds

millisecond

Return value

Returns true if the connection was lost, false if the timeout was reached.

See also

wxSocketBase::InterruptWait, wxSocketBase::Wait


wxSocketBase::WaitForRead

bool WaitForRead(long seconds = -1, long millisecond = 0)

This function waits until the socket is readable. This might mean that queued data is available for reading or, for streamed sockets, that the connection has been closed, so that a read operation will complete immediately without blocking (unless the wxSOCKET_WAITALL flag is set, in which case the operation might still block).

Parameters

seconds

millisecond

Return value

Returns true if the socket becomes readable, false on timeout.

See also

wxSocketBase::InterruptWait, wxSocketBase::Wait


wxSocketBase::WaitForWrite

bool WaitForWrite(long seconds = -1, long millisecond = 0)

This function waits until the socket becomes writable. This might mean that the socket is ready to send new data, or for streamed sockets, that the connection has been closed, so that a write operation is guaranteed to complete immediately (unless the wxSOCKET_WAITALL flag is set, in which case the operation might still block).

Parameters

seconds

millisecond

Return value

Returns true if the socket becomes writable, false on timeout.

See also

wxSocketBase::InterruptWait, wxSocketBase::Wait


wxSocketBase::Write

wxSocketBase& Write(const void * buffer, wxUint32 nbytes)

This function writes a buffer of nbytes bytes to the socket.

Use LastCount to verify the number of bytes actually written.

Use Error to determine if the operation succeeded.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

Remark/Warning

The exact behaviour of wxSocketBase::Write depends on the combination of flags being used. For a detailed explanation, see wxSocketBase::SetFlags.

See also

wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount, wxSocketBase::SetFlags


wxSocketBase::WriteMsg

wxSocketBase& WriteMsg(const void * buffer, wxUint32 nbytes)

This function writes a buffer of nbytes bytes from the socket, but it writes a short header before so that ReadMsg knows how much data should it actually read. So, a buffer sent with WriteMsg must be read with ReadMsg. This function always waits for the entire buffer to be sent, unless an error occurs.

Use LastCount to verify the number of bytes actually written.

Use Error to determine if the operation succeeded.

Parameters

buffer

nbytes

Return value

Returns a reference to the current object.

Remark/Warning

wxSocketBase::WriteMsg will behave as if the wxSOCKET_WAITALL flag was always set and it will always ignore the wxSOCKET_NOWAIT flag. The exact behaviour of WriteMsg depends on the wxSOCKET_BLOCK flag. For a detailed explanation, see wxSocketBase::SetFlags.

See also

wxSocketBase::Error, wxSocketBase::LastError, wxSocketBase::LastCount, wxSocketBase::SetFlags, wxSocketBase::ReadMsg