|
|
The extended socket class.
This class should be used instead of KSocket whenever the user needs fine-grained control over the socket being created. Unlike KSocket, which does everything at once, without much intervention, KExtendedSocket allows intervention at every step of the process and the setting of parameters.
This class allows for the creation of both server and client sockets. The only difference is that the passiveSocket flag must be passed either to the constructor or to setSocketFlags(). If passiveSocket is used, the class will enable functions listen() and accept() and related signals, and will also disable readBlock() and writeBlock().
To create a Unix socket, one would pass flag unixSocket to the constructor or setSocketFlags(). The hostname and service/port can be set to whatever is necessary. If no hostname is given, but a service/port is, the socket created will be implementation dependant (usually in /tmp). In any other case, the fields will be concatenated.
To create an Internet socket, inetSocket flag can be used. If, on the other hand a specific IP protocol is desired, ipv4Socket and/or ipv6Socket can be used.
Note that the socket type selection flags are cumulative. One could select Unix and Internet sockets by using unixSocket | inetSocket. Or, for instance, to make sure only IPv4 and IPv6 sockets are selected, even if future implementations support newer IP protocols, ipv4Socket | ipv6Socket is your guy.
enum Flags { anySocket = 0x00, knownSocket = 0x01, unixSocket = knownSocket | 0x02, inetSocket = knownSocket | 0x04, ipv4Socket = inetSocket | 0x100, ipv6Socket = inetSocket | 0x200, passiveSocket = 0x1000, canonName = 0x2000, noResolve = 0x4000, streamSocket = 0x8000, datagramSocket = 0x10000, rawSocket = 0x20000, inputBufferedSocket = 0x200000, outputBufferedSocket = 0x400000, bufferedSocket = 0x600000 } | Flags |
flags that can be passed down to the member functions
enum SockStatus { error = -1, nothing = 0, lookupInProgress = 4, lookupDone = 5, created = 10, bound = 11, connecting = 20, connected = 21, listening = 20, accepting = 21, closing = 35, done = 40 } | SockStatus |
status of the class The status are sequential. If a change to one status is requested, all the prior status will be passed and their actions, performed
KExtendedSocket ()
| KExtendedSocket |
Creates an empty KExtendedSocket
KExtendedSocket (const QString& host, int port, int flags = 0)
| KExtendedSocket |
Creates a socket with the given hostname and port
Parameters:
host | the hostname |
port | the port number |
flags | flags |
KExtendedSocket (const QString& host, const QString& service, int flags = 0)
| KExtendedSocket |
Creates a socket with the given hostname and service
Parameters:
host | the hostname |
serv | the service |
flags | flags |
~KExtendedSocket ()
| ~KExtendedSocket |
[virtual]
Destroys the socket, disconnecting if still connected and freeing any related resources still being kept.
inline int socketStatus ()
| socketStatus |
[const]
Returns the class status
inline int systemError ()
| systemError |
[const]
Returns the related system error code Except for IO_LookupError errors, these are codes found in errno
int setSocketFlags (int flags)
| setSocketFlags |
Sets the given flags. Will return the new flags status, or -1 if flags can no longer be set.
Parameters:
flags | the flags to be set |
inline int socketFlags ()
| socketFlags |
[const]
Returns the current flags
bool setHost (const QString& host)
| setHost |
Sets the hostname to the given value Returns true on success, false on error
Parameters:
host | the hostname |
QString host ()
| host |
[const]
Returns the hostname
bool setPort (int port)
| setPort |
Sets the port/service
Parameters:
port | the port |
bool setPort (const QString& service)
| setPort |
QString port ()
| port |
[const]
Returns the port/service
bool setAddress (const QString& host, int port)
| setAddress |
Sets the address where we will connect to
Parameters:
host | the hostname |
port | port number |
bool setAddress (const QString& host, const QString& serv)
| setAddress |
Sets the address where we will connect to
Parameters:
host | the hostname |
serv | the service |
bool setBindHost (const QString& host)
| setBindHost |
Sets the hostname to which we will bind locally before connecting. Returns false if this is a passiveSocket, otherwise true.
Parameters:
host | the hostname |
bool unsetBindHost ()
| unsetBindHost |
Unsets the bind hostname. That is, don't request a binding host.
inline QString bindHost ()
| bindHost |
[const]
Returns the hostname to which the socket will be/is bound
bool setBindPort (int port)
| setBindPort |
Sets the port/service to which we will bind before connecting
Parameters:
port | the port number |
bool setBindPort (const QString& service)
| setBindPort |
bool unsetBindPort ()
| unsetBindPort |
Unsets the bind port/service.
QString bindPort ()
| bindPort |
[const]
Returns the service to which the socket will be/is bound.
bool setBindAddress (const QString& host, int port)
| setBindAddress |
Sets both host and port to which we will bind the socket. Will return -1 if this is a passiveSocket
Parameters:
host | the hostname |
port | the port number |
bool setBindAddress (const QString& host, const QString& service)
| setBindAddress |
Sets both host and service to which we will bind the socket. Will return -1 if this is a passiveSocket
Parameters:
host | the hostname |
serv | the service |
bool unsetBindAddress ()
| unsetBindAddress |
Unsets the bind address for the socket. That means that we won't attempt to bind to an address before connecting
bool setTimeout (int secs, int usecs = 0)
| setTimeout |
Sets the timeout value for the connection, if this is not passiveSocket, or acception, if this is a passiveSocket. In the event the given function (connect or accept) returns due to time out, it's possible to call it again. Setting the timeout to 0 disables the timeout feature. Returns false if setting timeout makes no sense in the context.
Parameters:
secs | the timeout length, in seconds |
usecs | the timeout complement, in microseconds |
timeval timeout ()
| timeout |
[const]
Returns the timeout value for the connection
bool setBlockingMode (bool enable)
| setBlockingMode |
Sets/unsets blocking mode for the socket. When non-blocking mode is enabled, I/O operations might return error and set errno to EWOULDBLOCK. Also, it's not recommended to use this when using signals. Returns false on error.
Parameters:
enable | if true, set blocking mode. False, non-blocking mode. |
bool blockingMode ()
| blockingMode |
Returns the current blocking mode for this socket
bool setAddressReusable (bool enable)
| setAddressReusable |
Sets/unsets address reusing flag for this socket. This function returns true if the value was set correctly. That is NOT the result of the set.
Parameters:
enable | if true, set address reusable |
bool addressReusable ()
| addressReusable |
Returns whether this socket can be reused
bool setBufferSize (int rsize, int wsize = -2)
| setBufferSize |
[virtual]
Sets the buffer sizes for this socket.
This implementation allows any size for both parameters. The value given will be interpreted as the maximum size allowed for the buffers, after which the functions will stop buffering. The value of -1 will be interpreted as "unlimited" size.
Note: changing the buffer size to 0 for any buffer will cause the given buffer's to be discarded. Likewise, setting the size to a value less than the current size will cause the buffer to be shrunk to the wanted value, as if the data had been read.
Note 2: if we are not doing input buffering, the #ref closed signal will not be emitted for remote connection closing. That happens because we aren't reading from the connection, so we don't know when it closed.
Parameters:
rsize | read buffer size |
wsize | write buffer size |
Reimplemented from KBufferedIO.
const KSocketAddress * localAddress ()
| localAddress |
Returns the local socket address
const KSocketAddress * peerAddress ()
| peerAddress |
Returns the peer socket address. Use KExtendedSocket::resolve() to resolve this to a human-readable hostname/service or port.
inline int fd ()
| fd |
[const]
Returns the file descriptor
int lookup ()
| lookup |
[virtual]
Performs lookup on the addresses we were given before Returns 0 or an error. Codes are the same as for getaddrinfo This will perform lookups on the bind addresses if they were given
int startAsyncLookup ()
| startAsyncLookup |
[virtual]
Starts an asynchronous lookup for the addresses given This function returns 0 on success or -1 on error. Note that returning 0 means that either we are in the process of doing lookup or that it has finished already. When the lookup is done, the lookupReady signal will be emitted. Note that, depending on the parameters for the lookup, this function might know the results without the need for blocking or queueing an asynchronous lookup. That means that the lookupReady signal might be emitted by this function, so your code should be prepared for that. One such case is when noResolve flag is set. If this function were able to determine the results without queueing and we found an error during lookup, this function will return -1.
void cancelAsyncLookup ()
| cancelAsyncLookup |
[virtual]
Cancels any on-going asynchronous lookups
int listen (int N = 5)
| listen |
[virtual]
Place the socket in listen mode. The parameters are the same as for the system listen() call. Returns 0 on success, -1 on system error (errno available) and -2 if this is not a passiveSocket.
Parameters:
N | the queue length for pending connections |
int accept (KExtendedSocket *&sock)
| accept |
[virtual]
Accepts an incoming connection from the socket. If this socket is in blocking mode, this function will block until a connection is received. Otherwise, it might return with error. The sock parameter will be initialised with the newly created socket. Returns 0 on success, -1 on system error (errno set) and -2 if this is not a passiveSocket and -3 if this took too long (time out)
Parameters:
sock | a pointer to an KExtendedSocket variable |
int connect ()
| connect |
[virtual]
Attempts to connect to the remote host. The return values are: 0: success -1: system error, errno was set accordingly -2: this socket cannot connect(); this is a passiveSocket. It can also mean that the function was unable to make a connection with the given bind address or that an asynchronous connection attempt is already in progress. -3: connection timed out
Reimplemented from QObject.
int startAsyncConnect ()
| startAsyncConnect |
[virtual]
Starts an asynchronous connect. This works exactly the same as connect, except that the connection result won't be returned. This function will return either 0 on successful queueing of the connect or -1 on error. If this function returns 0, then the connectionSuccess or the connectionFailed signals will be emitted. Note that those signals might be emitted before this function returns, so your code should be prepared for that condition.
void cancelAsyncConnect ()
| cancelAsyncConnect |
[virtual]
Cancels any on-going asynchronous connection attempt.
bool open (int mode = IO_Raw | IO_ReadWrite)
| open |
[virtual]
Implementation of QIODevice's open() pure virtual function. This depends on the target host address already being there. If this is a passiveSocket, this is identical to call listen(); else, if this is not a passiveSocket and no connection attempt is in progress, this is like connect(). If one is in progress, this function will fail.
Parameters:
mode | the open mode. Must be IO_Raw | IO_ReadWrite |
Reimplemented from QIODevice.
void close ()
| close |
[virtual]
Closes the socket. If we have data still in the write buffer yet to be sent, the socket won't be closed right now. It'll be closed after we managed to send everything out. If you want to close the socket now, you may want to call flush first, and then closeNow.
Reimplemented from QIODevice.
void closeNow ()
| closeNow |
[virtual]
Closes the socket now, discarding the contents of the write buffer, if any. The read buffer's contents are kept until they are emptied by read operations or the class is destroyed.
Reimplemented from KBufferedIO.
void release ()
| release |
[virtual]
Releases the socket and anything we have holding on it. The class cannot be used anymore. In other words, this is just like closeNow(), but it does not actually close the socket. This is useful if you just want to connect and don't need the rest of the class. Note that the buffers' contents will be discarded. And usage of this method is discouraged, because the socket created might be such that normal library routines can't handle (read, write, close, etc.)
void flush ()
| flush |
[virtual]
Flushes the socket buffer. You need not call this method during normal operation as we will try and send everything as soon as possible. However, if you want to make sure that data in the buffer is being sent at this moment, you can call this function. It will try to send as much data as possible, but it will stop as soon as the kernel cannot receive any more data, and would possibly block. By repeatedly calling this function, the behaviour will be like that of a blocking socket. Indeed, if this function is called with the kernel not ready to receive data, it will block, unless this is a non-blocking socket. This function does not touch the read buffer. You can empty it by calling readBlock with a null destination buffer.
Reimplemented from QIODevice.
inline uint size ()
| size |
[const virtual]
Returns length of this socket. This call is not supported on sockets
Reimplemented from QIODevice.
inline int at ()
| at |
[const virtual]
Returns relative position from start. This call is not supported on sockets
Reimplemented from QIODevice.
inline bool at (int)
| at |
[virtual]
Returns true if we are at position. This is not supported on sockets
Reimplemented from QIODevice.
inline bool atEnd ()
| atEnd |
[const virtual]
Returns true if we are at the end. This is not supported on sockets, but we always are at the end in a socket...
Reimplemented from QIODevice.
int readBlock (char *data, uint maxlen)
| readBlock |
[virtual]
reads a block of data from the socket
If the socket is not buffered, this function will simply call the underlying read method. This function will block if the socket is not on non-blocking mode (see setBlockingMode) and there is not enough data to be read in the Operating System yet. If we are in non-blocking operation, the call will fail in this case. However, if we are buffering, this function will instead read from the buffer while there is available data. This function will never block in buffering mode, which means that if you try to read while the buffers are empty, this function will always return -1 and set the system error to EWOULDBLOCK (aka EAGAIN), so as to mimic non-blocking operation.
The return value for this function is the number of bytes effectively
read. If the data
param is not null, then this is also the number
of bytes copied into that buffer. If the return value is different than
maxlen
, then this function encountered a situation in which no more
bytes were available. Subsequent calls might cause this function to one
of these behaviours:
- block, if we are not buffering and we are not in non-blocking mode
- return an error, with EWOULDBLOCK system error, if we buffering
or we are in non-blocking mode
This function returns 0, if the function detected end-of-file condition
(socket was closed)
Parameters:
data | where we will write the read data to |
maxlen | maximum length of data to be read |
Reimplemented from QIODevice.
int writeBlock (const char *data, uint len)
| writeBlock |
[virtual]
writes a block of data to the socket
If the socket is not buffered, this function will simply call the underlying write method. This means that the function might block if that method blocks as well. That situation is possible if we are not in non-blocking mode and the operating system buffers are full for this socket. If we are in non-blocking mode and the operating system buffers are full, this function will return -1 and the system error will be set to EWOULDBLOCK. If we are buffering, this function will simply transfer the data into the write buffer. This function will always succeed, as long as there is enough room in the buffer. If the buffer size was limited and that limit is reached, this function will copy no more bytes than that limit. Trying to write with a full buffer will return -1 and set system error to EWOULDBLOCK.
The function returns the number of bytes written from data
buffer.
The return value might be less than len
if the output buffers cannot
accomodate that many bytes.
Parameters:
data | the data to write |
len | the length of data to write |
Reimplemented from QIODevice.
int peekBlock (char *data, uint maxlen)
| peekBlock |
[virtual]
peeks at a block of data from the socket This is exactly like read, except that the data won't be flushed from the read buffer. If this socket is not buffered, this function will always return with 0 bytes copied. The return value of 0 does not mean end-of-file condition.
Parameters:
data | where to store the data |
maxlen | how many bytes to copy, at most |
Reimplemented from KBufferedIO.
int unreadBlock (const char *data, uint len)
| unreadBlock |
[virtual]
reimplementation of unreadBlock method. This is so because unreading in sockets doesn't make sense, so this function will always return -1 (error) and set the system error to ENOSYS.
Reimplemented from KBufferedIO.
int waitForMore (int msec)
| waitForMore |
[virtual]
Waits msec
milliseconds for more data to be available, or 0 to
wait forever. The return value is the amount of data available for
read in the read buffer.
This function returns -1 in case of system error and -2 in case of
invalid socket state
Parameters:
msec | milliseconds to wait |
Reimplemented from KBufferedIO.
int getch ()
| getch |
[virtual]
gets a single character from the stream
Reimplemented from QIODevice.
int putch (int ch)
| putch |
[virtual]
writes a single character to the stream
Parameters:
ch | character to write, converted to char |
Reimplemented from QIODevice.
int ungetch (int)
| ungetch |
[virtual]
unreads one character from the stream. This is not possible on sockets
Reimplemented from QIODevice.
void enableRead (bool enable)
| enableRead |
[virtual]
Toggles the emission of the readyRead signal Note that this signal is emitted every time more data is available to be read, so you might get flooded with it being emitted every time, when in non-buffered mode. However, in buffered mode, this signal will be emitted only when there is data coming in from the wire. By default, this flag is set to false, i.e., signal not being emitted.
Parameters:
enable | if true, the signal will be emitted |
Reimplemented from KAsyncIO.
void enableWrite (bool enable)
| enableWrite |
[virtual]
Toggles the emission of the readyWrite signal Note that this signal is emitted only when the OS is ready to receive more data, which means that the write buffer is empty. And when that is reached, this signal will possibly be emitted on every loop, so you might want to disable it. By default, this flag is set to false.
Parameters:
enable | if true, the signal will be emitted |
Reimplemented from KAsyncIO.
void lookupFinished (int count)
| lookupFinished |
[signal]
This signal is emitted whenever an asynchronous lookup process is done.
The parameter count
tells how many results were found.
void connectionSuccess ()
| connectionSuccess |
[signal]
This signal is emitted whenever we connected asynchronously to a host.
void connectionFailed (int error)
| connectionFailed |
[signal]
This signal is emitted whenever our asynchronous connection attempt failed to all hosts listed.
Parameters:
error | the errno code of the last connection attempt |
int m_flags | m_flags |
[protected]
int m_status | m_status |
[protected]
int m_syserror | m_syserror |
[protected]
int sockfd | sockfd |
[protected]
void socketActivityRead ()
| socketActivityRead |
[protected slots slot]
void socketActivityWrite ()
| socketActivityWrite |
[protected slots slot]
void dnsResultsReady ()
| dnsResultsReady |
[protected slots slot]
void startAsyncConnectSlot ()
| startAsyncConnectSlot |
[protected slots slot]
void connectionEvent ()
| connectionEvent |
[protected slots slot]
void setError (int errorkind, int error)
| setError |
[protected]
Sets the error code
inline void cleanError ()
| cleanError |
[protected]
int doLookup (const QString& host, const QString& serv, addrinfo& hint,
kde_addrinfo** result)
| doLookup |
[protected static]
This is actually a wrapper around getaddrinfo()
int resolve (sockaddr* sock, ksocklen_t len, QString& host, QString& port, int flags = 0)
| resolve |
[static]
Performs resolution on the given socket address That is, tries to resolve the raw form of the socket address into a textual representation.
Parameters:
sockaddr | the socket address |
host | where the hostname will be written |
port | where the service-port will be written |
flags | the same flags as getnameinfo() |
int resolve (KSocketAddress* sock, QString& host, QString& port, int flags = 0)
| resolve |
[static]
QList<KAddressInfo> lookup (const QString& host, const QString& port, int flags = 0, int *error = 0)
| lookup |
[static]
Performs lookup on the given hostname/port combination and returns a list of matching addresses. The error code can be transformed into string by KExtendedSocket::strError with code of IO_LookupError.
IMPORTANT: the result values of the QList must be deleted after use. So, if you don't copy the KAddressInfo objects, the best way to assure that is to call setAutoDelete(true) on the list right after this function returns. If you do copy the results out, you must assure that the objects get deleted when they are not needed any more.
Parameters:
host | the hostname to look up |
port | the port/service to look up |
flags | flags to be used when looking up, @see Flags |
error | pointer to a variable holding the error code |
KSocketAddress * localAddress (int fd)
| localAddress |
[static]
Returns the local socket address Remember to delete the returned object when it is no longer needed.
Parameters:
fd | the file descriptor |
KSocketAddress * peerAddress (int fd)
| peerAddress |
[static]
Returns the peer socket address. Use KExtendedSocket::resolve() to resolve this to a human-readable hostname/service or port. Remember to delete the returned object when it is no longer needed.
Parameters:
fd | the file descriptor |
QString strError (int code, int syserr)
| strError |
[static]
Returns the representing text of this error code
Parameters:
code | the error code, as seen in status() |
syserr | the system error, as from systemError() |