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

QAbstractSocket Class Reference

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

#include <QAbstractSocket>

Inherits QIODevice.

Inherited by QTcpSocket and QUdpSocket.

Note: All the functions in this class are reentrant.

Writable Properties

Public Functions

Public Slots

Signals

Static Public Members

Protected Functions


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 socketState()). The initial state is Qt::UnconnectedState. After calling connectToHost(), the socket first enters Qt::HostLookupState. If the host is found, QAbstractSocket enters Qt::ConnectingState and emits the hostFound() signal. When the connection has been established, it enters Qt::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.

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 close(). QAbstractSocket enters Qt::ClosingState, then emits closing(). After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters Qt::ClosedState, and emits closed(). If you want to abort a connection immediately, discarding all pending data, call abort() instead.

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:

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.


Member Function Documentation

QAbstractSocket::QAbstractSocket ( Qt::SocketType socketType, QObject * parent )

Creates a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.

See also socketType(), QTcpSocket, and QUdpSocket.

QAbstractSocket::~QAbstractSocket ()   [virtual]

Destroys the socket.

void QAbstractSocket::abort ()

Aborts the current connection and resets the socket. Unlike close(), this function immediately closes the socket, clearing any pending data in the write buffer.

See also close().

Q_LONGLONG QAbstractSocket::bytesAvailable () const   [virtual]

Returns the number of incoming bytes that are waiting to be read.

Reimplemented from QIODevice.

See also bytesToWrite() and read().

Q_LONGLONG QAbstractSocket::bytesToWrite () const   [virtual]

Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush() is called.

Reimplemented from QIODevice.

See also bytesAvailable() and flush().

bool QAbstractSocket::canReadLine () const   [virtual]

Returns true if a line of data can be read from the socket; otherwise returns false.

Reimplemented from QIODevice.

See also readLine().

void QAbstractSocket::close ()   [virtual]

Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter Qt::ClosingState and wait until all data has been written. Eventually, it will enter Qt::ClosedState and emit the closed() signal.

Reimplemented from QIODevice.

See also abort().

void QAbstractSocket::closed ()   [signal]

This signal is emitted when the connection has been closed.

See also connectToHost() and close().

void QAbstractSocket::closing ()   [signal]

This signal is emitted when the connection is closing, before any pending data has been written to the network.

QAbstractSocket stops receiving data (and no longer emits readyRead()) after closing() has been emitted. Any pending data is still available, and can still be read, but no more data will be read from the network.

See also closed().

void QAbstractSocket::connectToHost ( const QString & hostName, Q_UINT16 port, OpenMode openMode = ReadWrite )

Attempts to make a connection to hostName on port port.

QAbstractSocket first enters Qt::HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters Qt::ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters Qt::ConnectedState and emits connected().

At any point, the socket can emit error() to signal that an error occurred.

hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "www.trolltech.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.

See also socketState(), peerName(), peerAddress(), peerPort(), and waitForConnected().

void QAbstractSocket::connectToHost ( const QHostAddress & address, Q_UINT16 port, OpenMode openMode = ReadWrite )

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

Attempts to make a connection to address on port port.

void QAbstractSocket::connected ()   [signal]

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

See also connectToHost() and connectionClosed().

void QAbstractSocket::error ( int socketError )   [signal]

This signal is emitted after an error occurred. The socketError parameter is a Qt::SocketError value.

See also socketError() and errorString().

bool QAbstractSocket::flush ()   [virtual]

Writes any pending outgoing data to the socket. Returns true if all data was successfully written; otherwise returns false. If it returns false, you can call socketError() to determine the cause of the error.

This function blocks until all data has been written or until the default timeout has expired.

Reimplemented from QIODevice.

See also setDefaultTimeout().

void QAbstractSocket::hostFound ()   [signal]

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

See also connected().

bool QAbstractSocket::isValid () const

Returns true if the socket is valid and ready for use; otherwise returns false.

See also socketState().

QHostAddress QAbstractSocket::localAddress () const

Returns the host address of the local socket if available; otherwise returns QHostAddress::Null.

This is normally the main IP address of the host, but can be QHostAddress::LocalHost (127.0.0.1) for connections to the local host.

See also localPort() and peerAddress().

Q_UINT16 QAbstractSocket::localPort () const

Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.

See also localAddress() and peerPort().

QHostAddress QAbstractSocket::peerAddress () const

Returns the address of the connected peer if the socket is in Qt::ConnectedState; otherwise returns QHostAddress::Null.

See also peerName(), peerPort(), and localAddress().

QString QAbstractSocket::peerName () const

Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.

See also peerAddress() and peerPort().

Q_UINT16 QAbstractSocket::peerPort () const

Returns the port of the connected peer if the socket is in Qt::ConnectedState; otherwise returns 0.

See also peerAddress() and localPort().

Q_LONGLONG QAbstractSocket::readBufferSize () const

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call read() or readAll().

A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.

See also setReadBufferSize() and read().

void QAbstractSocket::setReadBufferSize ( Q_LONGLONG size )

Sets the size of QAbstractSocket's internal read buffer to be size bytes.

If the buffer size is limited to a certain size, QAbstractSocket won't buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.

This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.

See also readBufferSize() and read().

bool QAbstractSocket::setSocketDescriptor ( int socketDescriptor, Qt::SocketState socketState = Qt::ConnectedState, OpenMode openMode = ReadWrite )

Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. QAbstractSocket enters the socket state specified by socketState.

See also socketDescriptor().

void QAbstractSocket::setSocketError ( Qt::SocketError socketError )   [protected]

Sets the type of error that last occurred to socketError.

See also setSocketState() and setErrorString().

void QAbstractSocket::setSocketState ( Qt::SocketState state )   [protected]

Sets the state of the socket to state.

See also state().

int QAbstractSocket::socketDescriptor () const

Returns the native socket descriptor of QAbstractSocket if this is available; otherwise returns -1.

The socket descriptor is not available when QAbstractSocket is in Qt::UnconnectedState.

See also setSocketDescriptor().

Qt::SocketError QAbstractSocket::socketError () const

Returns the type of error that last occurred.

See also socketState() and errorString().

Qt::SocketState QAbstractSocket::socketState () const

Returns the state of the socket.

See also socketError().

Qt::SocketType QAbstractSocket::socketType () const

Returns the socket type (TCP, UDP, or other).

See also QTcpSocket and QUdpSocket.

void QAbstractSocket::stateChanged ( int socketState )   [signal]

This signal is emitted whenever QAbstractSocket's state changes. The socketState parameter is a Qt::SocketState value.

See also socketState().

bool QAbstractSocket::waitForClosed ( int msecs = 30000 )

Waits until the socket is closed, up to msecs milliseconds. If the connection has been closed, this function returns true; otherwise it returns false. In the case where it returns false, you can call socketError() to determine the cause of the error.

The following example waits up to one second for a connection to be closed:

    socket->close();
    if (socket->waitForClosed(1000))
        qDebug("Closed!");

See also close() and closed().

bool QAbstractSocket::waitForConnected ( int msecs = 30000 )

Waits until the socket is connected, up to msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call socketError() to determine the cause of the error.

The following example waits up to one second for a connection to be established:

    socket->connectToHost("imap", 143);
    if (socket->waitForConnected(1000))
        qDebug("Connected!");

See also connectToHost() and connected().


Copyright © 2004 Trolltech Trademarks
Qt 4.0.0-b1