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 QObject and QIODevice.

Inherited by QTcpSocket and QUdpSocket.

Note: All the functions in this class are reentrant.

- List of all members, including inherited members

### Writable Properties

- 1 writable property inherited from QObject

### Public Functions

- QAbstractSocket ( Qt::SocketType socketType, QObject * parent )
- virtual ~QAbstractSocket ()
- virtual void abort ()
- virtual Q_LONGLONG at () const
- virtual Q_LONGLONG bytesAvailable () const
- virtual Q_LONGLONG bytesToWrite () const
- virtual bool canReadLine () const
- virtual void close ()
- virtual bool connectToHost ( const QString & hostName, Q_UINT16 port )
- bool connectToHost ( const QHostAddress & address, Q_UINT16 port )
- QString errorString () const
- virtual void flush ()
- bool isBlocking () const
- virtual bool isValid () const
- QHostAddress localAddress () const
- Q_UINT16 localPort () const
- QHostAddress peerAddress () const
- QString peerName () const
- Q_UINT16 peerPort () const
- virtual Q_LONGLONG read ( char * data, Q_LONGLONG maxSize )
- virtual Q_LONGLONG readBufferSize () const
- virtual QByteArray readLine ()
- void setBlocking ( bool blocking, int msec = 30000 )
- virtual void setReadBufferSize ( Q_LONGLONG size )
- bool setSocketDescriptor ( int socketDescriptor, Qt::SocketState socketState = Qt::ConnectedState )
- virtual Q_LONGLONG size () const
- int socketDescriptor () const
- Qt::SocketError socketError () const
- Qt::SocketState socketState () const
- Qt::SocketType socketType () const
- virtual bool waitForReadyRead ( int msecs = 30000 )
- virtual Q_LONGLONG write ( const char * data, Q_LONGLONG size )

- 24 public functions inherited from QObject
- 36 public functions inherited from QIODevice

### Public Slots

- 1 public slot inherited from QObject

### Signals

- void bytesWritten ( Q_LONGLONG numBytes )
- void closed ()
- void closing ()
- void connected ()
- void error ( int socketError )
- void hostFound ()
- void readyRead ()
- void stateChanged ( int socketState )

- 1 signal inherited from QObject

### Static Public Members

- 4 static public members inherited from QObject

### Protected Functions

- 9 protected functions inherited from QObject
- 2 protected functions inherited from QIODevice

## 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 three options:

- Instantiate QTcpSocket or QUdpSocket.
- Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.
- Subclass QAbstractSocket and implement your own socket type (e.g., for Unix domain sockets or Windows named pipes).

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.

By default, QAbstractSocket is non-blocking (asynchronous). This can be changed by calling setBlocking(true). In blocking mode, many functions (notably connectToHost(), read(), write(), and close()) do not return until their operation has completed; in non-blocking mode, all functions except waitForReadyRead() return immediately.

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.

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 getch(), putch(), and ungetch() 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.

Since QAbstractSocket inherits QIODevice, it can be used with QTextStream and QDataStream's stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: In non-blocking mode, 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 () `[virtual]`

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::at () const `[virtual]`

Always returns 0.

Reimplemented from QIODevice.

### Q_LONGLONG QAbstractSocket::bytesAvailable () const `[virtual]`

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

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.

See also bytesAvailable() and flush().

### void QAbstractSocket::bytesWritten ( Q_LONGLONG numBytes ) `[signal]`

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

See also write() and bytesToWrite().

### bool QAbstractSocket::canReadLine () const `[virtual]`

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

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.

See also closed().

### bool QAbstractSocket::connectToHost ( const QString & hostName, Q_UINT16 port ) `[virtual]`

Attempts to make a connection to hostName on port port. Returns true if the connection has been established; otherwise returns false.

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(), and peerPort().

### bool QAbstractSocket::connectToHost ( const QHostAddress & address, Q_UINT16 port )

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().

### QString QAbstractSocket::errorString () const

Returns the type of error that last occurred as a human-readable string.

See also socketError().

### void QAbstractSocket::flush () `[virtual]`

Writes any pending outgoing data to the socket.

If the socket is in blocking mode, this function blocks until all data has been written or until the timeout has expired; otherwise, the function writes as much as it can without blocking.

Reimplemented from QIODevice.

See also setBlocking().

### void QAbstractSocket::hostFound () `[signal]`

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

See also connected().

### bool QAbstractSocket::isBlocking () const

Returns true if the socket is blocking; otherwise returns false.

See also setBlocking().

### bool QAbstractSocket::isValid () const `[virtual]`

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::read ( char * data, Q_LONGLONG maxSize ) `[virtual]`

Reads at most maxSize bytes from the socket into data. Returns the number of bytes read, or -1 if an error occurred.

If the socket is in blocking mode and no data is available (i.e., bytesAvailable() returns 0), this function will block until data is available or until the timeout expires.

Reimplemented from QIODevice.

See also readLine(), readAll(), getch(), write(), and setBlocking().

### Q_LONGLONG QAbstractSocket::readBufferSize () const `[virtual]`

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().

### QByteArray QAbstractSocket::readLine () `[virtual]`

Reads a '\n'-terminated line of ASCII data from the socket and returns it as a QByteArray (including the '\n'). If no line can be read, it returns an empty QByteArray.

If the socket is in blocking mode, this function will block until a whole line can be read or until the timeout expires.

Reimplemented from QIODevice.

See also canReadLine() and setBlocking().

### void QAbstractSocket::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 any data, this class buffers the data and you can read it later, but no signal is emitted until new data arrives. A good practice is to read all data in the slot connected to this signal unless you need to receive more data to be able to process it.

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

### void QAbstractSocket::setBlocking ( bool blocking, int msec = 30000 )

If blocking is true, sets the socket to blocking mode and the timeout to msec milliseconds (the default timeout is 30 seconds); otherwise, sets the socket to non-blocking mode (msec is ignored).

In blocking mode, connectToHost(), read(), write(), readLine(), getch(), putch(), and close() suspend the program's execution until their task has been completed or until the timeout has expired. For example:

        QTcpSocket socket;
        socket.setBlocking(true);
        if (socket.connectToHost("imap", 143)) {
            qDebug("Connected!");
        } else {
            qDebug("Unable to connect: %s", socket.errorString().latin1());
        }

Blocking mode is the only option in applications that do not have an event loop.

See also isBlocking() and waitForReadyRead().

### void QAbstractSocket::setReadBufferSize ( Q_LONGLONG size ) `[virtual]`

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 )

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().

### Q_LONGLONG QAbstractSocket::size () const `[virtual]`

Same as bytesAvailable().

Reimplemented from QIODevice.

### 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::waitForReadyRead ( int msecs = 30000 ) `[virtual]`

Waits until there is data available for reading, up to msecs milliseconds. Returns true if there is data available; otherwise returns false. In the case where it returns false, you can call socketError() to determine the cause of the error.

This function is blocking regardless of whether setBlocking() was called or not, but is most commonly used in blocking mode to achieve a semi-non-blocking behavior.

The following example waits up to one second for a line of data to arrive:

        if (socket->waitForReadyRead(1000) && socket->canReadLine()) {
            QByteArray line = socket->readLine();
            qDebug("Read line: %s", line.ascii());
        }

See also setBlocking() and readyRead().

### Q_LONGLONG QAbstractSocket::write ( const char * data, Q_LONGLONG size ) `[virtual]`

Writes size bytes to the socket from data. Returns the number of bytes written, or -1 if an error occurred.

If the socket is in blocking mode, this function will block until all the data is written to the network. In non-blocking mode, this function always returns immediately; to force the data to be written, call flush().

Reimplemented from QIODevice.

See also putch(), read(), and setBlocking().