QAbstractSocket Class

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

Header: #include <QAbstractSocket>
qmake: QT += network
Inherits: QIODevice
Inherited By:

QTcpSocket and QUdpSocket

Note: All functions in this class are reentrant.

Public Types

enum BindFlag { ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform }
enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, AnyIPProtocol, UnknownNetworkLayerProtocol }
enum PauseMode { PauseNever, PauseOnSslErrors }
enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, SocketResourceError, …, UnknownSocketError }
enum SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption, TypeOfServiceOption, …, PathMtuSocketOption }
enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, BoundState, …, ListeningState }
enum SocketType { TcpSocket, UdpSocket, SctpSocket, UnknownSocketType }

Detailed Description

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:

  • Instantiate QTcpSocket or QUdpSocket.
  • Create a native socket descriptor, instantiate QAbstractSocket, and call setSocketDescriptor() to wrap the native socket.

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, errorOccurred() 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. The bytesWritten() signal is emitted when data has been written to the socket. Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal.

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. After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket::UnconnectedState, 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 errorOccurred(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:

  • waitForConnected() blocks until a connection has been established.
  • waitForReadyRead() blocks until new data is available for reading.
  • waitForBytesWritten() blocks until one payload of data has been written to the socket.
  • waitForDisconnected() blocks until the connection has closed.

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 fortuneclient and blockingfortuneclient examples for an overview of both approaches.

Note: We discourage the use of the blocking functions together with signals. One of the two possibilities should be used.

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 QNetworkAccessManager and QTcpServer.

Member Type Documentation

enum QAbstractSocket::BindFlag

This enum describes the different flags you can pass to modify the behavior of QAbstractSocket::bind().

ConstantValueDescription
QAbstractSocket::ShareAddress0x1Allow other services to bind to the same address and port. This is useful when multiple processes share the load of a single service by listening to the same address and port (e.g., a web server with several pre-forked listeners can greatly improve response time). However, because any service is allowed to rebind, this option is subject to certain security considerations. Note that by combining this option with ReuseAddressHint, you will also allow your service to rebind an existing shared address. On Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows, this is the default behavior, so this option is ignored.
QAbstractSocket::DontShareAddress0x2Bind the address and port exclusively, so that no other services are allowed to rebind. By passing this option to QAbstractSocket::bind(), you are guaranteed that on success, your service is the only one that listens to the address and port. No services are allowed to rebind, even if they pass ReuseAddressHint. This option provides more security than ShareAddress, but on certain operating systems, it requires you to run the server with administrator privileges. On Unix and macOS, not sharing is the default behavior for binding an address and port, so this option is ignored. On Windows, this option uses the SO_EXCLUSIVEADDRUSE socket option.
QAbstractSocket::ReuseAddressHint0x4Provides a hint to QAbstractSocket that it should try to rebind the service even if the address and port are already bound by another socket. On Windows and Unix, this is equivalent to the SO_REUSEADDR socket option.
QAbstractSocket::DefaultForPlatform0x0The default option for the current platform. On Unix and macOS, this is equivalent to (DontShareAddress + ReuseAddressHint), and on Windows, it is equivalent to ShareAddress.

This enum was introduced or modified in Qt 5.0.

enum QAbstractSocket::NetworkLayerProtocol

This enum describes the network layer protocol values used in Qt.

ConstantValueDescription
QAbstractSocket::IPv4Protocol0IPv4
QAbstractSocket::IPv6Protocol1IPv6
QAbstractSocket::AnyIPProtocol2Either IPv4 or IPv6
QAbstractSocket::UnknownNetworkLayerProtocol-1Other than IPv4 and IPv6

See also QHostAddress::protocol().

enum QAbstractSocket::PauseMode

This enum describes the behavior of when the socket should hold back with continuing data transfer. The only notification currently supported is QSslSocket::sslErrors().

ConstantValueDescription
QAbstractSocket::PauseNever0x0Do not pause data transfer on the socket. This is the default and matches the behavior of Qt 4.
QAbstractSocket::PauseOnSslErrors0x1Pause data transfer on the socket upon receiving an SSL error notification. I.E. QSslSocket::sslErrors().

This enum was introduced or modified in Qt 5.0.

enum QAbstractSocket::SocketError

This enum describes the socket errors that can occur.

ConstantValueDescription
QAbstractSocket::ConnectionRefusedError0The connection was refused by the peer (or timed out).
QAbstractSocket::RemoteHostClosedError1The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent.
QAbstractSocket::HostNotFoundError2The host address was not found.
QAbstractSocket::SocketAccessError3The socket operation failed because the application lacked the required privileges.
QAbstractSocket::SocketResourceError4The local system ran out of resources (e.g., too many sockets).
QAbstractSocket::SocketTimeoutError5The socket operation timed out.
QAbstractSocket::DatagramTooLargeError6The datagram was larger than the operating system's limit (which can be as low as 8192 bytes).
QAbstractSocket::NetworkError7An error occurred with the network (e.g., the network cable was accidentally plugged out).
QAbstractSocket::AddressInUseError8The address specified to QAbstractSocket::bind() is already in use and was set to be exclusive.
QAbstractSocket::SocketAddressNotAvailableError9The address specified to QAbstractSocket::bind() does not belong to the host.
QAbstractSocket::UnsupportedSocketOperationError10The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support).
QAbstractSocket::ProxyAuthenticationRequiredError12The socket is using a proxy, and the proxy requires authentication.
QAbstractSocket::SslHandshakeFailedError13The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket)
QAbstractSocket::UnfinishedSocketOperationError11Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background).
QAbstractSocket::ProxyConnectionRefusedError14Could not contact the proxy server because the connection to that server was denied
QAbstractSocket::ProxyConnectionClosedError15The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established)
QAbstractSocket::ProxyConnectionTimeoutError16The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase.
QAbstractSocket::ProxyNotFoundError17The proxy address set with setProxy() (or the application proxy) was not found.
QAbstractSocket::ProxyProtocolError18The connection negotiation with the proxy server failed, because the response from the proxy server could not be understood.
QAbstractSocket::OperationError19An operation was attempted while the socket was in a state that did not permit it.
QAbstractSocket::SslInternalError20The SSL library being used reported an internal error. This is probably the result of a bad installation or misconfiguration of the library.
QAbstractSocket::SslInvalidUserDataError21Invalid data (certificate, key, cypher, etc.) was provided and its use resulted in an error in the SSL library.
QAbstractSocket::TemporaryError22A temporary error occurred (e.g., operation would block and socket is non-blocking).
QAbstractSocket::UnknownSocketError-1An unidentified error occurred.

See also QAbstractSocket::error() and QAbstractSocket::errorOccurred().

enum QAbstractSocket::SocketOption

This enum represents the options that can be set on a socket. If desired, they can be set after having received the connected() signal from the socket or after having received a new socket from a QTcpServer.

ConstantValueDescription
QAbstractSocket::LowDelayOption0Try to optimize the socket for low latency. For a QTcpSocket this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1 to enable.
QAbstractSocket::KeepAliveOption1Set this to 1 to enable the SO_KEEPALIVE socket option
QAbstractSocket::MulticastTtlOption2Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
QAbstractSocket::MulticastLoopbackOption3Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.
QAbstractSocket::TypeOfServiceOption4This option is not supported on Windows. This maps to the IP_TOS socket option. For possible values, see table below.
QAbstractSocket::SendBufferSizeSocketOption5Sets the socket send buffer size in bytes at the OS level. This maps to the SO_SNDBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers. This enum value has been introduced in Qt 5.3.
QAbstractSocket::ReceiveBufferSizeSocketOption6Sets the socket receive buffer size in bytes at the OS level. This maps to the SO_RCVBUF socket option. This option does not affect the QIODevice or QAbstractSocket buffers (see setReadBufferSize()). This enum value has been introduced in Qt 5.3.
QAbstractSocket::PathMtuSocketOption7Retrieves the Path Maximum Transmission Unit (PMTU) value currently known by the IP stack, if any. Some IP stacks also allow setting the MTU for transmission. This enum value was introduced in Qt 5.11.

Possible values for TypeOfServiceOption are:

ValueDescription
224Network control
192Internetwork control
160CRITIC/ECP
128Flash override
96Flash
64Immediate
32Priority
0Routine

This enum was introduced or modified in Qt 4.6.

See also QAbstractSocket::setSocketOption() and QAbstractSocket::socketOption().

enum QAbstractSocket::SocketState

This enum describes the different states in which a socket can be.

ConstantValueDescription
QAbstractSocket::UnconnectedState0The socket is not connected.
QAbstractSocket::HostLookupState1The socket is performing a host name lookup.
QAbstractSocket::ConnectingState2The socket has started establishing a connection.
QAbstractSocket::ConnectedState3A connection is established.
QAbstractSocket::BoundState4The socket is bound to an address and port.
QAbstractSocket::ClosingState6The socket is about to close (data may still be waiting to be written).
QAbstractSocket::ListeningState5For internal use only.

See also QAbstractSocket::state().

enum QAbstractSocket::SocketType

This enum describes the transport layer protocol.

ConstantValueDescription
QAbstractSocket::TcpSocket0TCP
QAbstractSocket::UdpSocket1UDP
QAbstractSocket::SctpSocket2SCTP
QAbstractSocket::UnknownSocketType-1Other than TCP, UDP and SCTP

See also QAbstractSocket::socketType().