QWebSocket Class
The QWebSocket class is a WebSocket connection, as a client or as one end accepted by a server. More…
| Header | #include <QWebSocket> |
|---|---|
| CMake | target_link_libraries(app PRIVATE Nt::WebSockets) |
| Module | Nt WebSockets C++ Classes |
| Since | 5.3 |
| Inherits | QObject |
List of all members, including inherited members
Public Functions
Public Slots
| void | close(QWebSocketProtocol::CloseCode closeCode = QWebSocketProtocol::CloseCodeNormal, const QString &reason = QString()) |
| void | open(const QUrl &url) |
| void | open(const QNetworkRequest &request) |
| void | open(const QUrl &url, const QWebSocketHandshakeOptions &options) |
| void | open(const QNetworkRequest &request, const QWebSocketHandshakeOptions &options) |
| void | ping(const QByteArray &payload = QByteArray()) |
| void | ignoreSslErrors() |
Signals
| void | aboutToClose() |
| void | connected() |
| void | disconnected() |
| void | stateChanged(QAbstractSocket::SocketState state) |
| void | readChannelFinished() |
| void | textFrameReceived(const QString &frame, bool isLastFrame) |
| void | binaryFrameReceived(const QByteArray &frame, bool isLastFrame) |
| void | textMessageReceived(const QString &message) |
| void | binaryMessageReceived(const QByteArray &message) |
| void | errorOccurred(QAbstractSocket::SocketError error) |
| void | pong(quint64 elapsedTime, const QByteArray &payload) |
| void | bytesWritten(qint64 bytes) |
| void | sslErrors(const QList<QSslError> &errors) |
| void | peerVerifyError(const QSslError &error) |
Static Public Members
| quint64 | maxIncomingMessageSize() |
| quint64 | maxIncomingFrameSize() |
| quint64 | maxOutgoingFrameSize() |
Detailed Description
A QWebSocket sends and receives messages over the WebSocket protocol (RFC 6455). As a client, call open() with a ws: or wss: URL; the socket connects, performs the opening handshake, and emits connected(). A QWebSocketServer, or a QAbstractHttpServer that accepts an upgrade, hands out sockets that are already connected.
QWebSocket socket;
QObject::connect(&socket, &QWebSocket::connected, [&] {
std::printf("connected, subprotocol \"%s\"\n", qPrintable(socket.subprotocol()));
socket.sendTextMessage(text);
});
QObject::connect(&socket, &QWebSocket::textMessageReceived, [&](const QString &message) {
std::printf("received: %s\n", qPrintable(message));
socket.close();
});
QObject::connect(&socket, &QWebSocket::disconnected, &app, &QCoreApplication::quit);
QObject::connect(&socket, &QWebSocket::errorOccurred, [&](QAbstractSocket::SocketError) {
std::fprintf(stderr, "error: %s\n", qPrintable(socket.errorString()));
app.exit(1);
});
Messages are text (a QString, sent as UTF-8) or binary (a QByteArray). They arrive whole through textMessageReceived() and binaryMessageReceived(), and also frame by frame through textFrameReceived() and binaryFrameReceived(). Pings are answered automatically; ping() measures the round trip.
close() starts the closing handshake: a close frame with a code and a reason goes to the peer, which answers with its own, and then the connection closes and disconnected() is emitted. closeCode() and closeReason() say why a connection closed. A peer that breaks the protocol, for example by sending text that is not UTF-8, is sent a close frame with the matching code, and the connection is closed.
Incoming frames and messages are limited by setMaxAllowedIncomingFrameSize() and setMaxAllowedIncomingMessageSize(), 64 MiB each by default. A frame is received completely before it is reported.
See also QWebSocketServer and Using Nt WebSockets.
Differences from Qt
No extensions are negotiated, so there is no permessage-deflate compression. There is no proxy support, no readBufferSize(), no pauseMode(), no pre-shared keys and no continueInterruptedHandshake(). A client has no timeout for the opening handshake. Only version 13 of the protocol is spoken. Host names are resolved synchronously, as by QAbstractSocket::connectToHost().
Member Function Documentation
QWebSocket::QWebSocket(const QString &origin = QString(), QWebSocketProtocol::Version version = QWebSocketProtocol::VersionLatest, QObject *parent = nullptr)
Constructs an unconnected WebSocket with the given parent. A client sends origin in the Origin header of the opening handshake, if it is not empty. version must be QWebSocketProtocol::VersionLatest or QWebSocketProtocol::Version13, the only version spoken.
See also open().
QWebSocket::~QWebSocket()
Destroys the socket. An open connection is aborted, without a closing handshake; call close() first to end it cleanly.
void QWebSocket::abort()
Aborts the connection at once, without a closing handshake, and discards data not written yet.
See also close().
void QWebSocket::aboutToClose()
This signal is emitted when the closing handshake begins, either because close() was called or because the peer sent a close frame.
See also close() and disconnected().
void QWebSocket::binaryFrameReceived(const QByteArray &frame, bool isLastFrame)
This signal is emitted for each binary frame received, with its payload frame. isLastFrame is true for the last frame of a message.
See also binaryMessageReceived().
void QWebSocket::binaryMessageReceived(const QByteArray &message)
This signal is emitted when a complete binary message has been received.
See also binaryFrameReceived() and sendBinaryMessage().
qint64 QWebSocket::bytesToWrite() const
Returns the number of bytes waiting to be written to the network.
void QWebSocket::bytesWritten(qint64 bytes)
This signal is emitted when bytes bytes have been written to the network.
See also bytesToWrite().
void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode = QWebSocketProtocol::CloseCodeNormal, const QString &reason = QString())
Starts the closing handshake with closeCode and reason. The reason is cut to 123 bytes of UTF-8. disconnected() is emitted when the peer has answered and the connection has closed, or after five seconds without an answer. A socket still in the opening handshake is aborted.
See also abort() and closeCode().
QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
Returns the code of the closing handshake: the one sent by close(), or the one received from the peer. QWebSocketProtocol::CloseCodeAbnormalDisconnection means the connection ended without a closing handshake.
See also closeReason().
QString QWebSocket::closeReason() const
Returns the reason of the closing handshake.
See also closeCode().
void QWebSocket::connected()
This signal is emitted when the opening handshake has succeeded and messages can be sent.
See also open() and disconnected().
void QWebSocket::disconnected()
This signal is emitted when the connection has closed. closeCode() and closeReason() say why.
See also connected() and close().
QAbstractSocket::SocketError QWebSocket::error() const
Returns the type of the last error.
See also errorString() and errorOccurred().
void QWebSocket::errorOccurred(QAbstractSocket::SocketError error)
This signal is emitted when an error occurred, for example when the host cannot be reached or the opening handshake fails.
See also error() and errorString().
QString QWebSocket::errorString() const
Returns a description of the last error.
See also error().
bool QWebSocket::flush()
Writes as much buffered data to the network as possible without blocking. Returns true if any data was written.
QWebSocketHandshakeOptions QWebSocket::handshakeOptions() const
Returns the options given to open().
void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
Ignores the TLS errors when they occur while connecting. Call it before open(), or from a slot connected to sslErrors().
See also sslErrors().
void QWebSocket::ignoreSslErrors()
This is an overloaded function.
Ignores the TLS errors of the current handshake. Call it from a slot connected to sslErrors().
bool QWebSocket::isValid() const
Returns true if the socket is connected and messages can be sent; otherwise returns false.
See also state().
QHostAddress QWebSocket::localAddress() const
Returns the local address of the connection, or a null address if there is none.
quint16 QWebSocket::localPort() const
Returns the local port of the connection, or 0 if there is none.
const QMaskGenerator * QWebSocket::maskGenerator() const
Returns the mask generator set with setMaskGenerator(), or nullptr for the default one.
quint64 QWebSocket::maxAllowedIncomingFrameSize() const
Returns the largest incoming frame allowed, in bytes. The default is 64 MiB.
quint64 QWebSocket::maxAllowedIncomingMessageSize() const
Returns the largest incoming message allowed, in bytes. The default is 64 MiB.
quint64 QWebSocket::maxIncomingFrameSize()
Returns the largest value setMaxAllowedIncomingFrameSize() accepts: 1 GiB.
quint64 QWebSocket::maxIncomingMessageSize()
Returns the largest value setMaxAllowedIncomingMessageSize() accepts: 1 GiB.
quint64 QWebSocket::maxOutgoingFrameSize()
Returns the largest value setOutgoingFrameSize() accepts.
void QWebSocket::open(const QUrl &url)
Opens a connection to url, which must have the scheme ws or wss. connected() is emitted when the opening handshake has succeeded, and errorOccurred() if it fails.
See also close() and connected().
void QWebSocket::open(const QNetworkRequest &request)
This is an overloaded function.
Opens a connection to the URL of request, sending its raw headers in the opening handshake.
void QWebSocket::open(const QUrl &url, const QWebSocketHandshakeOptions &options)
This is an overloaded function.
Opens a connection to url, asking for the subprotocols in options.
void QWebSocket::open(const QNetworkRequest &request, const QWebSocketHandshakeOptions &options)
This is an overloaded function.
Opens a connection to the URL of request, with its raw headers and the subprotocols in options.
QString QWebSocket::origin() const
Returns the origin: the one given to the constructor for a client, or the Origin header the client sent for a server-side socket.
quint64 QWebSocket::outgoingFrameSize() const
Returns the size of the frames that outgoing messages are split into.
QHostAddress QWebSocket::peerAddress() const
Returns the address of the peer, or a null address if there is none.
QString QWebSocket::peerName() const
Returns the name of the peer, as given to open() for a client.
quint16 QWebSocket::peerPort() const
Returns the port of the peer, or 0 if there is none.
void QWebSocket::peerVerifyError(const QSslError &error)
This signal is emitted for each error found while verifying the server's certificate, before sslErrors().
void QWebSocket::ping(const QByteArray &payload = QByteArray())
Sends a ping with payload, cut to 125 bytes. The peer answers with a pong, reported by pong() with the round-trip time.
void QWebSocket::pong(quint64 elapsedTime, const QByteArray &payload)
This signal is emitted when a pong arrives, with the payload of the ping and the round trip elapsedTime in milliseconds since the last ping() call.
See also ping().
void QWebSocket::readChannelFinished()
This signal is emitted when no more data will be received.
QNetworkRequest QWebSocket::request() const
Returns the request of the opening handshake. For a server-side socket it holds the header fields the client sent.
See also requestUrl().
QUrl QWebSocket::requestUrl() const
Returns the URL the client opened, or that a client requested from the server.
See also request().
QString QWebSocket::resourceName() const
Returns the path and query of the requested URL, such as /chat?room=1.
See also requestUrl().
qint64 QWebSocket::sendBinaryMessage(const QByteArray &data)
Sends data as a binary message and returns the number of bytes sent, or 0 if the socket is not connected.
See also sendTextMessage() and binaryMessageReceived().
qint64 QWebSocket::sendTextMessage(const QString &message)
Sends message as a text message, encoded in UTF-8, and returns the number of bytes sent, or 0 if the socket is not connected. Messages longer than outgoingFrameSize() are sent in several frames.
See also sendBinaryMessage() and textMessageReceived().
void QWebSocket::setMaskGenerator(const QMaskGenerator *maskGenerator)
Sets the generator of masking keys to maskGenerator, or back to the default, which uses the system's random number generator, if it is nullptr. The generator is not owned by the socket and must outlive it. Only clients mask their frames.
void QWebSocket::setMaxAllowedIncomingFrameSize(quint64 maxAllowedIncomingFrameSize)
Sets the largest incoming frame to maxAllowedIncomingFrameSize bytes, at most maxIncomingFrameSize(). A larger frame closes the connection with QWebSocketProtocol::CloseCodeTooMuchData.
void QWebSocket::setMaxAllowedIncomingMessageSize(quint64 maxAllowedIncomingMessageSize)
Sets the largest incoming message to maxAllowedIncomingMessageSize bytes, at most maxIncomingMessageSize(). A larger message closes the connection with QWebSocketProtocol::CloseCodeTooMuchData.
void QWebSocket::setOutgoingFrameSize(quint64 outgoingFrameSize)
Sets the size of the frames that outgoing messages are split into to outgoingFrameSize bytes. The default is 512 KiB.
void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
Sets the TLS configuration of wss: connections to sslConfiguration. It takes effect on the next open().
See also sslConfiguration().
QSslConfiguration QWebSocket::sslConfiguration() const
Returns the TLS configuration of the connection, or the one set with setSslConfiguration() before it is open.
void QWebSocket::sslErrors(const QList<QSslError> &errors)
This signal is emitted when verifying the server's certificate found errors. Unless a connected slot calls ignoreSslErrors(), the connection is closed.
See also ignoreSslErrors().
QAbstractSocket::SocketState QWebSocket::state() const
Returns the state of the socket: UnconnectedState, ConnectingState while the TCP connection and the opening handshake are made, ConnectedState, or ClosingState during the closing handshake.
See also stateChanged().
void QWebSocket::stateChanged(QAbstractSocket::SocketState state)
This signal is emitted when the state of the socket changes to state.
See also state().
QString QWebSocket::subprotocol() const
Returns the subprotocol chosen in the opening handshake, or an empty string if there is none.
See also QWebSocketHandshakeOptions::setSubprotocols() and QWebSocketServer::setSupportedSubprotocols().
void QWebSocket::textFrameReceived(const QString &frame, bool isLastFrame)
This signal is emitted for each text frame received. frame holds the complete characters of the frame, and isLastFrame is true for the last frame of a message. A character split between two frames is reported with the second one.
See also textMessageReceived().
void QWebSocket::textMessageReceived(const QString &message)
This signal is emitted when a complete text message has been received.
See also textFrameReceived() and sendTextMessage().
QWebSocketProtocol::Version QWebSocket::version() const
Returns the version of the WebSocket protocol in use.