QWebSocketServer Class
The QWebSocketServer class accepts WebSocket connections. More…
| Header | #include <QWebSocketServer> |
|---|---|
| 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 Types
| enum | SslMode |
Public Functions
Signals
| void | acceptError(QAbstractSocket::SocketError socketError) |
| void | serverError(QWebSocketProtocol::CloseCode closeCode) |
| void | originAuthenticationRequired(QWebSocketCorsAuthenticator *pAuthenticator) |
| void | newConnection() |
| void | closed() |
| void | sslErrors(const QList<QSslError> &errors) |
| void | peerVerifyError(const QSslError &error) |
Detailed Description
A QWebSocketServer listens on a TCP port, answers the opening handshake of each client, and hands out a connected QWebSocket for each one through newConnection() and nextPendingConnection():
QWebSocketServer server(QStringLiteral("Nt echo"), QWebSocketServer::NonSecureMode);
if (!server.listen(QHostAddress::LocalHost, port)) {
std::fprintf(stderr, "cannot listen: %s\n", qPrintable(server.errorString()));
return 1;
}
QObject::connect(&server, &QWebSocketServer::newConnection, [&server] {
QWebSocket *socket = server.nextPendingConnection();
QObject::connect(socket, &QWebSocket::textMessageReceived, socket,
[socket](const QString &message) { socket->sendTextMessage(message); });
QObject::connect(socket, &QWebSocket::binaryMessageReceived, socket,
[socket](const QByteArray &message) { socket->sendBinaryMessage(message); });
QObject::connect(socket, &QWebSocket::disconnected, socket, &QObject::deleteLater);
});
In SecureMode, the server speaks TLS (wss:) with the configuration set by setSslConfiguration(), which must hold a certificate and a private key.
The server checks every opening handshake before it accepts a client: the request must be a GET for HTTP/1.1 with a Host header, the Upgrade and Connection fields, a valid Sec-WebSocket-Key and version 13. A client asking for another version gets 426 Upgrade Required; other bad requests get 400 Bad Request. A client that does not complete its handshake within handshakeTimeoutMS() is disconnected. Connect to originAuthenticationRequired() to accept only some origins, which browsers send in the Origin header.
Accepted sockets are children of the server. Delete them when done, or they are deleted with the server.
See also QWebSocket and Using Nt WebSockets.
Differences from Qt
There is no proxy support, no pre-shared keys and no alertSent() or handshakeInterruptedOnError() signals. peerVerifyError() is never emitted. The handshake request may not exceed 16 KiB.
Member Type Documentation
enum QWebSocketServer::SslMode
Whether the server encrypts its connections.
| Constant | Description |
|---|---|
QWebSocketServer::SecureMode | The server speaks TLS: its URL has the scheme wss. |
QWebSocketServer::NonSecureMode | The server does not encrypt: its URL has the scheme ws. |
Member Function Documentation
QWebSocketServer::QWebSocketServer(const QString &serverName, SslMode secureMode, QObject *parent = nullptr)
Constructs a WebSocket server with the given parent. serverName is sent in the Server header of the opening handshake, and secureMode says whether the server speaks TLS. The server does not listen until listen() is called.
QWebSocketServer::~QWebSocketServer()
Destroys the server, closing it if it is listening. Sockets it accepted are deleted too.
void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
This signal is emitted when accepting a TCP connection failed with socketError.
See also error().
void QWebSocketServer::close()
Stops listening and emits closed(). Accepted sockets stay open.
void QWebSocketServer::closed()
This signal is emitted when the server stops listening.
See also close().
QWebSocketProtocol::CloseCode QWebSocketServer::error() const
Returns the code of the last handshake error.
See also errorString() and serverError().
QString QWebSocketServer::errorString() const
Returns a description of the last error.
void QWebSocketServer::handleConnection(QTcpSocket *socket) const
Performs the opening handshake on socket, a connected TCP socket that was accepted elsewhere, and emits newConnection() when it succeeds. The server takes ownership of the socket.
int QWebSocketServer::handshakeTimeoutMS() const
Returns the time a client has to complete its opening handshake, in milliseconds.
bool QWebSocketServer::hasPendingConnections() const
Returns true if accepted sockets are waiting for nextPendingConnection(); otherwise returns false.
bool QWebSocketServer::isListening() const
Returns true if the server is listening; otherwise returns false.
bool QWebSocketServer::listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0)
Starts listening on address and port, or a free port if port is 0. Returns true on success; otherwise sets errorString() and returns false.
See also close() and serverUrl().
int QWebSocketServer::maxPendingConnections() const
Returns the largest number of accepted sockets waiting for nextPendingConnection().
void QWebSocketServer::newConnection()
This signal is emitted each time a client has completed the opening handshake. Call nextPendingConnection() to take it.
See also hasPendingConnections().
QWebSocket * QWebSocketServer::nextPendingConnection()
Returns the next accepted socket, or nullptr if there is none. The socket is connected and a child of the server.
See also newConnection().
void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *pAuthenticator)
This signal is emitted during the opening handshake of each client, before it is accepted. A connected slot reads the Origin header from pAuthenticator, with origin(), and calls setAllowed(false) on it to refuse the client with 403 Forbidden. Clients are allowed if no slot refuses them.
The authenticator is only valid during the call.
void QWebSocketServer::pauseAccepting()
Stops accepting new TCP connections until resumeAccepting() is called.
void QWebSocketServer::peerVerifyError(const QSslError &error)
This signal is emitted for each error found while verifying a client certificate.
void QWebSocketServer::resumeAccepting()
Accepts new TCP connections again after pauseAccepting().
SslMode QWebSocketServer::secureMode() const
Returns whether the server speaks TLS.
QHostAddress QWebSocketServer::serverAddress() const
Returns the address the server listens on.
void QWebSocketServer::serverError(QWebSocketProtocol::CloseCode closeCode)
This signal is emitted when the opening handshake of a client failed; closeCode says why and errorString() describes it.
See also error().
QString QWebSocketServer::serverName() const
Returns the name sent in the Server header of the opening handshake.
quint16 QWebSocketServer::serverPort() const
Returns the port the server listens on, or 0 if it is not listening.
QUrl QWebSocketServer::serverUrl() const
Returns the URL clients connect to, such as ws://127.0.0.1:1234, or an empty URL if the server is not listening.
void QWebSocketServer::setHandshakeTimeout(int msec)
Sets the time a client has to complete its opening handshake to msec milliseconds. The default is 10 seconds.
void QWebSocketServer::setMaxPendingConnections(int numConnections)
Sets the largest number of accepted sockets that wait for nextPendingConnection() to numConnections. Clients beyond it are refused with 503 Service Unavailable. The default is 30.
void QWebSocketServer::setServerName(const QString &serverName)
Sets the name sent in the Server header of the opening handshake to serverName.
bool QWebSocketServer::setSocketDescriptor(qintptr socketDescriptor)
Makes the server listen on the already listening native socket socketDescriptor. Returns true on success.
void QWebSocketServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
Sets the TLS configuration of a server in SecureMode to sslConfiguration. It takes effect when listen() is called.
void QWebSocketServer::setSupportedSubprotocols(const QStringList &protocols)
Sets the subprotocols the server supports to protocols. Of the ones a client asks for, the first that the server supports is chosen, and QWebSocket::subprotocol() returns it.
qintptr QWebSocketServer::socketDescriptor() const
Returns the native socket the server listens on, or -1.
QSslConfiguration QWebSocketServer::sslConfiguration() const
Returns the TLS configuration of the server.
void QWebSocketServer::sslErrors(const QList<QSslError> &errors)
This signal is emitted when the TLS handshake with a client found errors.
QStringList QWebSocketServer::supportedSubprotocols() const
Returns the subprotocols the server supports.
QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
Returns the versions of the protocol the server speaks: only version 13.