Home · Overviews · Examples 

QAbstractSocket Class Reference
[com.trolltech.qt.network module]

The QAbstractSocket class provides the base functionality common to all socket types. More...

Inherits QIODevice.

Inherited by QTcpSocket and QUdpSocket.


Detailed Description

The QAbstractSocket class provides the base functionality common to all socket types.

QAbstractSocket is the base class for QTcpSocket and QUdpSocket and contains all common functionality of these two classes. If you need a socket, you have two options:

TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. UDP (User Datagram Protocol) is an unreliable, datagram-oriented, connectionless protocol. In practice, this means that TCP is better suited for continuous transmission of data, whereas the more lightweight UDP can be used when reliability isn't important.

QAbstractSocket's API unifies most of the differences between the two protocols. For example, although UDP is connectionless, connectToHost() establishes a virtual connection for UDP sockets, enabling you to use QAbstractSocket in more or less the same way regardless of the underlying protocol. Internally, QAbstractSocket remembers the address and port passed to connectToHost(), and functions like read and write use these values.

At any time, QAbstractSocket has a state (returned by state). The initial state is UnconnectedState. After calling connectToHost(), the socket first enters HostLookupState. If the host is found, QAbstractSocket enters ConnectingState and emits the hostFound signal. When the connection has been established, it enters ConnectedState and emits connected. If an error occurs at any stage, error is emitted. Whenever the state changes, stateChanged is emitted. For convenience, isValid returns true if the socket is ready for reading and writing, but note that the socket's state must be ConnectedState before reading and writing can occur.

Read or write data by calling read or write, or use the convenience functions readLine and readAll. QAbstractSocket also inherits getChar(), putChar(), and ungetChar() from QIODevice, which work on single bytes. For every chunk of data that has been written to the socket, the bytesWritten signal is emitted.

The readyRead signal is emitted every time a new chunk of data has arrived. bytesAvailable then returns the number of bytes that are available for reading. Typically, you would connect the readyRead signal to a slot and read all available data there. If you don't read all the data at once, the remaining data will still be available later, and any new incoming data will be appended to QAbstractSocket's internal read buffer. To limit the size of the read buffer, call setReadBufferSize.

To close the socket, call disconnectFromHost. QAbstractSocket enters QAbstractSocket::ClosingState, then emits closing(). After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::ClosedState, and emits disconnected. If you want to abort a connection immediately, discarding all pending data, call abort instead. If the remote host closes the connection, QAbstractSocket will emit error(QAbstractSocket::RemoteHostClosedError), during which the socket state will still be ConnectedState, and then the disconnected signal will be emitted.

The port and address of the connected peer is fetched by calling peerPort() and peerAddress. peerName returns the host name of the peer, as passed to connectToHost(). localPort() and localAddress return the port and address of the local socket.

QAbstractSocket provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking sockets:

We show an example:

        int numRead = 0, numReadTotal = 0;
        char buffer[50];

        forever {
            numRead  = socket.read(buffer, 50);

            // do whatever with array

            numReadTotal += numRead;
            if (numRead == 0 && !socket.waitForReadyRead())
                break;
        }

If waitForReadyRead() returns false, the connection has been closed or an error has occurred.

Programming with a blocking socket is radically different from programming with a non-blocking socket. A blocking socket doesn't require an event loop and typically leads to simpler code. However, in a GUI application, blocking sockets should only be used in non-GUI threads, to avoid freezing the user interface. See the network/fortuneclient and network/blockingfortuneclient examples for an overview of both approaches.

QAbstractSocket can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: You must make sure that enough data is available before attempting to read it using operator>>().

See also QFtp, QHttp, and QTcpServer.


Copyright © 2007 Trolltech Trademarks
Qt Jambi 4.3.2_01