Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions

QSocket Class Reference

The QSocket class provides a buffered TCP connection. More...

#include <QSocket>

Inherits QObject and QIODevice.

Note: All the functions in this class are reentrant.

Public Types

Writable Properties

Public Functions

Public Slots

Signals

Static Public Members

Protected Functions


Detailed Description

The QSocket class provides a buffered TCP connection.

QSocket provides a totally non-blocking QIODevice, modifying and extending the API of QIODevice with socket-specific code.

The functions you're likely to call most are connectToHost(), bytesAvailable(), canReadLine(), and the ones it inherits from QIODevice.

connectToHost() is the most used function. As its name implies, it opens a connection to a named host.

Most network protocols are either packet-oriented or line-oriented. canReadLine() indicates whether a connection contains an entire unread line or not, and bytesAvailable() returns the number of bytes available for reading.

The signals error(), connected(), readyRead() and connectionClosed() inform you of the progress of the connection. There are also some less commonly used signals. hostFound() is emitted when connectToHost() has finished its DNS lookup and is starting its TCP connection. delayedCloseFinished() is emitted when close() succeeds. bytesWritten() is emitted when QSocket moves data from its "to be written" queue into the TCP implementation.

There are several access functions for the socket: state() returns whether the object is idle, is doing a DNS lookup, is connecting, has an operational connection, etc. The address() and port() functions return the IP address and port used for the connection. The peerAddress() and peerPort() functions return the IP address and port used by the peer, and peerName() returns the name of the peer (normally the name that was passed to connectToHost()). socket() returns a pointer to the QSocketDevice used for this socket.

QSocket inherits QIODevice, and reimplements some functions. In general, you can treat it as a QIODevice for writing, and mostly also for reading. The match isn't perfect, since the QIODevice API is designed for devices that are controlled by the same machine, and an asynchronous peer-to-peer network connection isn't quite like that. For example, there is nothing that matches QIODevice::size() exactly. The documentation for open(), close(), flush(), size(), at(), atEnd(), read(), write(), getch(), putch(), ungetch(), and readLine() describe the differences in detail.

See also QSocketDevice, QHostAddress, and QSocketNotifier.


Member Type Documentation

enum QSocket::Error

This enum specifies the possible errors:

QSocket::ErrConnectionRefusedThe connection was refused.
QSocket::ErrHostNotFoundThe host was not found.
QSocket::ErrSocketReadA read from the socket failed.

enum QSocket::State

This enum defines the connection states:

QSocket::IdleThere is no connection.
QSocket::HostLookupA DNS lookup is in progress.
QSocket::ConnectingA TCP connection is being established.
QSocket::ConnectedThere is an operational connection.
QSocket::ClosingThe socket is closing down, but is not yet closed.

Member Function Documentation

QSocket::QSocket ( QObject * parent = 0 )

Creates a QSocket object in the QSocket::Idle state.

The parent argument is passed on to the QObject constructor.

QSocket::QSocket ( QObject * parent, const char * name )

Use one of the constructors that doesn't take the name argument and then use setObjectName() instead.

QSocket::~QSocket ()   [virtual]

Destroys the socket, closing the connection if necessary.

See also close().

QHostAddress QSocket::address () const

Returns the host address of this socket. (This is normally the main IP address of the host, but can be 127.0.0.1 for connections to localhost.)

Q_ULONG QSocket::bytesAvailable () const

Returns the number of incoming bytes that can be read; i.e. the size of the input buffer. Equivalent to size().

See also bytesToWrite().

Q_ULONG QSocket::bytesToWrite () const

Returns the number of bytes that are waiting to be written; i.e. the size of the output buffer.

See also bytesAvailable() and clearPendingData().

void QSocket::bytesWritten ( int nbytes )   [signal]

This signal is emitted when data has been written to the network. The nbytes parameter specifies how many bytes were written.

The bytesToWrite() function is often used in the same context; it indicates how many buffered bytes there are left to write.

See also write() and bytesToWrite().

bool QSocket::canReadLine () const

Returns true if it is possible to read an entire line of text from this socket at this time; otherwise returns false.

Note that if the peer closes the connection unexpectedly, this function returns false. This means that loops such as the following won't work:

    while(!socket->canReadLine()) // WRONG
        ;

See also readLine().

void QSocket::clearPendingData ()

Deletes the data that is waiting to be written. This is useful if you want to close the socket without waiting for all the data to be written.

See also bytesToWrite(), close(), and delayedCloseFinished().

void QSocket::connectToHost ( const QString & host, Q_UINT16 port )   [virtual]

Attempts to make a connection to host on the specified port, returning immediately.

Any connection or pending connection is closed immediately, and QSocket goes into the HostLookup state. When the lookup succeeds, it emits hostFound(), starts a TCP connection and goes into the Connecting state. Finally, when the connection succeeds, it emits connected() and goes into the Connected state. If there is an error at any point, it emits error().

host may be an IP address in string form, or it may be a DNS name. QSocket will do a normal DNS lookup if required. Note that port is in native byte order, unlike some other libraries.

See also state().

void QSocket::connected ()   [signal]

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

See also connectToHost() and connectionClosed().

void QSocket::connectionClosed ()   [signal]

This signal is emitted when the other end has closed the connection. The read buffers may contain buffered input data which you can read after the connection was closed.

See also connectToHost() and close().

void QSocket::delayedCloseFinished ()   [signal]

This signal is emitted when a delayed close is finished.

If you call close(), and there is buffered output data to be written, QSocket goes into the QSocket::Closing state and returns immediately. It will then keep writing to the socket until all the data has been written. Then the delayedCloseFinished() signal is emitted.

See also close().

void QSocket::error ( int err )   [signal]

This signal is emitted after an error occurred. The err parameter contains an Error value.

void QSocket::hostFound ()   [signal]

This signal is emitted after connectToHost() has been called and the host lookup has succeeded.

See also connected().

QHostAddress QSocket::peerAddress () const

Returns the host address, as resolved from the name passed to the connectToHost() function.

QString QSocket::peerName () const

Returns the host name as specified to the connectToHost() function. An empty string is returned if none has been set.

Q_UINT16 QSocket::peerPort () const

Returns the peer's host port number, normally as specified to the connectToHost() function. If none has been set, this function returns 0.

Note that Qt always uses native byte order; i.e. 67 is 67 in Qt. There is no need to call htons().

Q_UINT16 QSocket::port () const

Returns the host port number of this socket in native byte order.

Q_ULONG QSocket::readBufferSize () const

Returns the size of the read buffer.

See also setReadBufferSize().

QByteArray QSocket::readLine ()   [virtual]

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a line of text including a terminating newline character (\n). Returns "" if canReadLine() returns false.

Reimplemented from QIODevice.

See also canReadLine().

void QSocket::readyRead ()   [signal]

This signal is emitted every time there is new incoming data.

Bear in mind that new incoming data is only reported once. If you do not read all the data, this class buffers the data; you can read it later, but no signal is emitted unless new data arrives. A good practice is to read all data in the slot connected to this signal, unless you are sure that you need to receive more data to be able to process it.

See also read(), readLine(), and bytesAvailable().

void QSocket::setReadBufferSize ( Q_ULONG bufSize )

Sets the size of the QSocket's internal read buffer to bufSize.

Usually QSocket reads all data that is available from the operating system's socket. If the buffer size is limited to a certain size, this means that the QSocket class doesn't buffer more than this size of data.

If the size of the read buffer is 0, the read buffer is unlimited and all incoming data is buffered. This is the default.

If you read the data in the readyRead() signal, you shouldn't use this option since it might slow down your program unnecessarily. This option is useful if you only need to read the data at certain points in time, like in a realtime streaming application.

See also readBufferSize().

void QSocket::setSocket ( int socket )   [virtual]

Sets the socket in use to the socket given, and the state() to Connected. The socket must already be connected.

This allows us to use the QSocket class as a wrapper for other socket types (e.g. Unix Domain Sockets).

void QSocket::setSocketDevice ( QSocketDevice * device )   [virtual]

Sets the internal socket device to device. Passing a device of 0 will cause the internal socket device to be used. Any existing connection will be disconnected before using the new device.

The new device should not be connected before being associated with a QSocket; after setting the socket call connectToHost() to make the connection.

This function is useful if you need to subclass QSocketDevice and want to use the QSocket API; for example, to implement Unix domain sockets.

int QSocket::socket () const

Returns the socket number, or -1 if there is no socket at the moment.

QSocketDevice * QSocket::socketDevice ()

Returns a pointer to the internal socket device.

There is normally no need to manipulate the socket device directly since this class will configure it sufficiently for most applications.

State QSocket::state () const

Returns the current state of the socket connection.

See also QSocket::State.

int QSocket::ungetch ( int ch )   [virtual]

This implementation of the virtual function QIODevice::ungetch() prepends the character ch to the read buffer so that the next read returns this character as the first character of the output.

Reimplemented from QIODevice.

Q_ULONG QSocket::waitForMore ( int msecs, bool * timeout = 0 ) const

Wait up to msecs milliseconds for more data to be available.

If msecs is -1 the call will block indefinitely.

Returns the number of bytes available.

If timeout is non-null and no error occurred (i.e. it does not return -1): this function sets *timeout to true, if the reason for returning was that the timeout was reached; otherwise it sets *timeout to false. This is useful to find out if the peer closed the connection.

Warning: This is a blocking call and should be avoided in event-driven applications.

See also bytesAvailable().


Copyright © 2004 Trolltech. Trademarks
Qt 4.0.0-tp2