QAbstractSocket Class
The QAbstractSocket class is the base class of QTcpSocket and QUdpSocket. More…
| Header | #include <QAbstractSocket> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::Network) |
| Module | Nt Network C++ Classes |
| Inherits | QIODevice |
| Inherited by | QTcpSocket, QUdpSocket |
List of all members, including inherited members
Public Types
| enum | SocketType |
| enum | NetworkLayerProtocol |
| enum | SocketError |
| enum | SocketState |
| enum | SocketOption |
| enum | BindFlag |
| typedef | BindMode |
Public Functions
| QAbstractSocket(SocketType socketType, QObject *parent) | |
| ~QAbstractSocket() | |
| virtual void | connectToHost(const QString &hostName, quint16 port, OpenMode mode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol) |
| virtual void | connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite) |
| virtual void | disconnectFromHost() |
| bool | bind(const QHostAddress &address, quint16 port = 0, BindMode mode = DefaultForPlatform) |
| bool | bind(quint16 port = 0, BindMode mode = DefaultForPlatform) |
| bool | isValid() const |
| bool | flush() |
| void | abort() |
| quint16 | localPort() const |
| QHostAddress | localAddress() const |
| quint16 | peerPort() const |
| QHostAddress | peerAddress() const |
| QString | peerName() const |
| qint64 | readBufferSize() const |
| void | setReadBufferSize(qint64 size) |
| virtual qintptr | socketDescriptor() const |
| virtual bool | setSocketDescriptor(qintptr socketDescriptor, SocketState state = ConnectedState, OpenMode openMode = ReadWrite) |
| virtual void | setSocketOption(SocketOption option, const QVariant &value) |
| virtual QVariant | socketOption(SocketOption option) |
| SocketType | socketType() const |
| SocketState | state() const |
| SocketError | error() const |
| virtual bool | waitForConnected(int msecs = 30000) |
| virtual bool | waitForDisconnected(int msecs = 30000) |
Reimplemented Public Functions
| qint64 | bytesAvailable() const |
| qint64 | bytesToWrite() const |
| bool | canReadLine() const |
| bool | isSequential() const |
| void | close() |
| bool | waitForReadyRead(int msecs = 30000) |
| bool | waitForBytesWritten(int msecs = 30000) |
Signals
| void | hostFound() |
| void | connected() |
| void | disconnected() |
| void | stateChanged(QAbstractSocket::SocketState state) |
| void | errorOccurred(QAbstractSocket::SocketError error) |
Protected Functions
| void | setSocketState(SocketState state) |
| void | setSocketError(SocketError error, const QString &text) |
| void | setSocketErrorFromErrno(int err) |
| bool | createSocket(int family) |
| int | socketFamily() const |
| virtual void | readActivated() |
Reimplemented Protected Functions
Detailed Description
QAbstractSocket is a non-blocking, event-loop driven socket built on POSIX sockets. Call connectToHost() to connect, or bind() to receive datagrams, then react to the connected(), readyRead() and disconnected() signals:
QTcpSocket socket;
QObject::connect(&socket, &QTcpSocket::connected, [&] { socket.write("hello\n"); });
socket.connectToHost("localhost", 8080);
The waitFor...() functions block the calling thread by polling the socket and can be used without an event loop.
See also QTcpSocket, QUdpSocket and QTcpServer.
Differences from Qt
Host names are resolved synchronously inside connectToHost(), so hostFound() is emitted before the function returns. There is no proxy or SSL support: the proxy functions, proxyAuthenticationRequired() and the related error values are declared or omitted but never produced. pauseMode(), setPauseMode(), resume(), setLocalPort() and the other protected peer/local setters are not available. Sockets must be used from a single thread.
On Zephyr the number of sockets is bounded by CONFIG_ZVFS_OPEN_MAX, CONFIG_NET_MAX_CONTEXTS and CONFIG_NET_MAX_CONN. The more sockets a thread serves, the more groups its event loop polls, which delays them slightly unless CONFIG_ZVFS_POLL_MAX is raised. See Nt on Zephyr.
Member Type Documentation
enum QAbstractSocket::BindFlag
This enum describes the different flags you can pass to modify the behavior of bind().
| Constant | Description |
|---|---|
QAbstractSocket::ShareAddress | Allows other services to bind to the same address and port (SO_REUSEADDR). |
QAbstractSocket::DontShareAddress | Binds the address and port exclusively. This is the behavior when no sharing flag is given. |
QAbstractSocket::ReuseAddressHint | Provides a hint that the address may be reused; treated like ShareAddress. |
QAbstractSocket::DefaultForPlatform | The default option for the current platform. No special options are set. |
See also BindMode.
typedef QAbstractSocket::BindMode
Stores an OR combination of BindFlag values.
enum QAbstractSocket::NetworkLayerProtocol
This enum describes the network layer protocol of an address.
| Constant | Description |
|---|---|
QAbstractSocket::IPv4Protocol | IPv4. |
QAbstractSocket::IPv6Protocol | IPv6. |
QAbstractSocket::AnyIPProtocol | Either IPv4 or IPv6 (a dual-stack address). |
QAbstractSocket::UnknownNetworkLayerProtocol | Neither IPv4 nor IPv6. |
enum QAbstractSocket::SocketError
This enum describes the socket errors that can occur.
| Constant | Description |
|---|---|
QAbstractSocket::ConnectionRefusedError | The connection was refused by the peer. |
QAbstractSocket::RemoteHostClosedError | The remote host closed the connection. |
QAbstractSocket::HostNotFoundError | The host address was not found. |
QAbstractSocket::SocketAccessError | The socket operation failed because the application lacked the required privileges. |
QAbstractSocket::SocketResourceError | The local system ran out of resources (for example, file descriptors). |
QAbstractSocket::SocketTimeoutError | The socket operation timed out. |
QAbstractSocket::DatagramTooLargeError | The datagram was larger than the operating system's limit. |
QAbstractSocket::NetworkError | An error occurred with the network (for example, the network was unreachable). |
QAbstractSocket::AddressInUseError | The address specified to bind() is already in use. |
QAbstractSocket::SocketAddressNotAvailableError | The address specified to bind() does not belong to the host. |
QAbstractSocket::UnsupportedSocketOperationError | The requested socket operation is not supported by the local operating system. |
QAbstractSocket::UnfinishedSocketOperationError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyAuthenticationRequiredError | Declared for source compatibility; not used. |
QAbstractSocket::SslHandshakeFailedError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyConnectionRefusedError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyConnectionClosedError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyConnectionTimeoutError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyNotFoundError | Declared for source compatibility; not used. |
QAbstractSocket::ProxyProtocolError | Declared for source compatibility; not used. |
QAbstractSocket::OperationError | An operation was attempted while the socket was in a state that did not permit it. |
QAbstractSocket::SslInternalError | Declared for source compatibility; not used. |
QAbstractSocket::SslInvalidUserDataError | Declared for source compatibility; not used. |
QAbstractSocket::TemporaryError | Declared for source compatibility; not used. |
QAbstractSocket::UnknownSocketError | An unidentified error occurred. |
enum QAbstractSocket::SocketOption
This enum represents the options that can be set on a socket. Use setSocketOption() and socketOption() to access them.
| Constant | Description |
|---|---|
QAbstractSocket::LowDelayOption | Disables Nagle's algorithm (TCP_NODELAY) when set to 1. |
QAbstractSocket::KeepAliveOption | Enables TCP keep-alive (SO_KEEPALIVE) when set to 1. |
QAbstractSocket::MulticastTtlOption | Sets the time-to-live (hop limit) of outgoing multicast datagrams. |
QAbstractSocket::MulticastLoopbackOption | Controls whether multicast datagrams are looped back to the local host. |
QAbstractSocket::TypeOfServiceOption | Sets the IP type-of-service field (IP_TOS). |
QAbstractSocket::SendBufferSizeSocketOption | Sets the socket send buffer size in bytes. |
QAbstractSocket::ReceiveBufferSizeSocketOption | Sets the socket receive buffer size in bytes. |
QAbstractSocket::PathMtuSocketOption | Declared for source compatibility; not supported. |
enum QAbstractSocket::SocketState
This enum describes the different states in which a socket can be.
| Constant | Description |
|---|---|
QAbstractSocket::UnconnectedState | The socket is not connected. |
QAbstractSocket::HostLookupState | The socket is performing a host name lookup. |
QAbstractSocket::ConnectingState | The socket has started establishing a connection. |
QAbstractSocket::ConnectedState | A connection is established. |
QAbstractSocket::BoundState | The socket is bound to an address and port. |
QAbstractSocket::ListeningState | For internal use only. |
QAbstractSocket::ClosingState | The socket is about to close; pending data is still being written. |
enum QAbstractSocket::SocketType
This enum describes the transport layer protocol of a socket.
| Constant | Description |
|---|---|
QAbstractSocket::TcpSocket | TCP, a reliable stream-oriented protocol. |
QAbstractSocket::UdpSocket | UDP, an unreliable datagram protocol. |
QAbstractSocket::SctpSocket | SCTP. Declared for source compatibility; not supported. |
QAbstractSocket::UnknownSocketType | Any other type. |
Member Function Documentation
QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)
Creates a new abstract socket of type socketType with the given parent. The socket starts in the UnconnectedState and no operating system socket exists until connectToHost() or bind() is called.
QAbstractSocket::~QAbstractSocket()
Destroys the socket and closes the underlying operating system socket without emitting disconnected().
void QAbstractSocket::abort()
Aborts the current connection and discards any pending outgoing data, then closes the socket.
See also disconnectFromHost() and close().
bool QAbstractSocket::bind(const QHostAddress &address, quint16 port = 0, BindMode mode = DefaultForPlatform)
Binds the socket to address on port using the given mode. A port of 0 lets the system choose a free port. Returns true on success, after which the socket is in BoundState; otherwise sets the error and returns false.
For UDP sockets, the socket is opened for reading and writing once bound. Binding to QHostAddress::Any creates a dual-stack socket when the system supports it.
See also localPort() and localAddress().
bool QAbstractSocket::bind(quint16 port = 0, BindMode mode = DefaultForPlatform)
This is an overloaded function.
Binds to QHostAddress::Any on port using the given mode.
qint64 QAbstractSocket::bytesAvailable() const
Reimplements QIODevice::bytesAvailable().
Returns the number of incoming bytes that are waiting to be read.
qint64 QAbstractSocket::bytesToWrite() const
Reimplements QIODevice::bytesToWrite().
Returns the number of bytes waiting to be written to the network.
bool QAbstractSocket::canReadLine() const
Reimplements QIODevice::canReadLine().
Returns true if a complete line of data can be read from the socket.
void QAbstractSocket::close()
Reimplements QIODevice::close().
Flushes pending data, closes the socket, discards any unread data and emits disconnected() if the socket was connected.
See also disconnectFromHost() and abort().
void QAbstractSocket::connected()
This signal is emitted after connectToHost() has been called and a connection has been successfully established.
See also connectToHost() and disconnected().
void QAbstractSocket::connectToHost(const QString &hostName, quint16 port, OpenMode mode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol)
Attempts to make a connection to hostName on the given port. The protocol parameter restricts the lookup to IPv4 or IPv6 addresses.
The host name is resolved synchronously and hostFound() is emitted. The socket then enters ConnectingState and connected() is emitted once the connection is established, or errorOccurred() if every address fails. The socket is opened in mode.
See also connected(), waitForConnected() and disconnectFromHost().
void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port, OpenMode mode = ReadWrite)
This is an overloaded function.
Attempts to make a connection to address on the given port. No host name lookup is performed, so hostFound() is not emitted.
bool QAbstractSocket::createSocket(int family)
Creates a non-blocking operating system socket of the given address family (AF_INET or AF_INET6) if none exists yet. Returns true if a socket is available; otherwise sets the error and returns false.
See also socketFamily().
void QAbstractSocket::disconnected()
This signal is emitted when the socket has been disconnected.
See also connectToHost(), disconnectFromHost() and abort().
void QAbstractSocket::disconnectFromHost()
Attempts to close the socket. If there is pending data waiting to be written, the socket enters ClosingState and closes once the data has been sent. Otherwise it closes immediately and emits disconnected().
See also connectToHost(), close() and abort().
SocketError QAbstractSocket::error() const
Returns the type of error that last occurred.
See also errorOccurred() and errorString().
void QAbstractSocket::errorOccurred(QAbstractSocket::SocketError error)
This signal is emitted after an error occurred. The error parameter describes the type of error.
See also error() and errorString().
bool QAbstractSocket::flush()
Attempts to send the queued outgoing data to the network without blocking. Returns true if at least one byte was sent; otherwise returns false.
See also bytesToWrite() and waitForBytesWritten().
void QAbstractSocket::hostFound()
This signal is emitted after connectToHost() has been called and the host lookup has succeeded.
See also connected().
bool QAbstractSocket::isSequential() const
Reimplements QIODevice::isSequential().
Returns true; sockets are sequential devices.
bool QAbstractSocket::isValid() const
Returns true if the socket is valid and ready for use, that is, an operating system socket exists; otherwise returns false.
QHostAddress QAbstractSocket::localAddress() const
Returns the host address of the local socket, or a null address if the socket is neither connected nor bound.
See also localPort() and peerAddress().
quint16 QAbstractSocket::localPort() const
Returns the host port number, in native byte order, of the local socket, or 0 if the socket is neither connected nor bound.
See also localAddress() and peerPort().
QHostAddress QAbstractSocket::peerAddress() const
Returns the address of the connected peer, or a null address if the socket is not connected.
See also peerName(), peerPort() and localAddress().
QString QAbstractSocket::peerName() const
Returns the name of the peer as specified to connectToHost(), or the peer address as a string if connectToHost() was given an address or the name is unknown.
See also peerAddress() and connectToHost().
quint16 QAbstractSocket::peerPort() const
Returns the port of the connected peer, or 0 if the socket is not connected.
See also peerAddress() and localPort().
void QAbstractSocket::readActivated()
Called when the operating system socket becomes readable. TCP sockets read the available bytes into the internal buffer and emit readyRead(); a zero-byte read closes the socket with RemoteHostClosedError. UDP sockets only emit readyRead() and leave the datagram queued.
qint64 QAbstractSocket::readBufferSize() const
Returns the size of the internal read buffer in bytes, or 0 if the buffer is unlimited.
See also setReadBufferSize().
qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
Reimplements QIODevice::readData().
Copies up to maxSize bytes from the internal read buffer into data and returns the number of bytes copied.
void QAbstractSocket::setReadBufferSize(qint64 size)
Sets the size of the internal read buffer to size bytes. If the buffer is full, the socket stops reading from the network until the application consumes data. A size of 0 (the default) means the buffer is unlimited.
See also readBufferSize() and read().
bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState state = ConnectedState, OpenMode openMode = ReadWrite)
Initializes the socket to use the existing operating system socket socketDescriptor, in the given state and openMode. The descriptor is switched to non-blocking mode and the socket takes ownership of it. Returns true on success; otherwise sets the error and returns false.
See also socketDescriptor().
void QAbstractSocket::setSocketError(SocketError error, const QString &text)
Sets the type of error that last occurred to error, sets the human-readable description to text and emits errorOccurred().
See also error() and errorString().
void QAbstractSocket::setSocketErrorFromErrno(int err)
Maps the POSIX error number err to a SocketError, uses strerror() as the error string and emits errorOccurred().
See also setSocketError().
void QAbstractSocket::setSocketOption(SocketOption option, const QVariant &value)
Sets option to value, converted to an integer. Does nothing if the socket has no operating system socket yet, the option is not supported or value cannot be converted.
See also socketOption().
void QAbstractSocket::setSocketState(SocketState state)
Sets the socket state to state and emits stateChanged() if the state actually changed.
See also state().
qintptr QAbstractSocket::socketDescriptor() const
Returns the native operating system socket descriptor, or -1 if the socket has none.
See also setSocketDescriptor().
int QAbstractSocket::socketFamily() const
Returns the address family of the operating system socket (AF_INET or AF_INET6), or 0 if there is none.
QVariant QAbstractSocket::socketOption(SocketOption option)
Returns the value of option as an int QVariant, or an invalid QVariant if the socket has no operating system socket or the option is not supported.
See also setSocketOption().
SocketType QAbstractSocket::socketType() const
Returns the socket type, TcpSocket or UdpSocket.
SocketState QAbstractSocket::state() const
Returns the state of the socket.
See also stateChanged().
void QAbstractSocket::stateChanged(QAbstractSocket::SocketState state)
This signal is emitted whenever the socket's state changes to state.
See also state().
bool QAbstractSocket::waitForBytesWritten(int msecs = 30000)
Reimplements QIODevice::waitForBytesWritten().
Blocks until at least some of the queued data has been written to the network, or until msecs milliseconds have passed. Returns true if data was written; otherwise returns false.
See also waitForReadyRead() and flush().
bool QAbstractSocket::waitForConnected(int msecs = 30000)
Waits until the socket is connected, up to msecs milliseconds (a negative value waits forever). Returns true if the connection has been established; otherwise returns false and, on a timeout, sets SocketTimeoutError.
See also connectToHost() and connected().
bool QAbstractSocket::waitForDisconnected(int msecs = 30000)
Waits until the socket has disconnected, up to msecs milliseconds. Returns true if the connection has been closed; otherwise returns false.
See also disconnectFromHost() and disconnected().
bool QAbstractSocket::waitForReadyRead(int msecs = 30000)
Reimplements QIODevice::waitForReadyRead().
Blocks until new data is available for reading and readyRead() has been emitted, or until msecs milliseconds have passed. Returns true if data arrived; otherwise returns false.
See also waitForBytesWritten().
qint64 QAbstractSocket::writeData(const char *data, qint64 maxSize)
Reimplements QIODevice::writeData().
Queues maxSize bytes from data for sending and returns maxSize. Returns -1 with OperationError if the socket is not connected.