1 /****************************************************************************
3 ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>.
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
43 \class QWebSocketServer
45 \inmodule QtWebSockets
47 \brief Implements a websocket-based server.
49 It is modeled after QTcpServer, and behaves the same. So, if you know how to use QTcpServer,
50 you know how to use QWebSocketServer.
51 This class makes it possible to accept incoming websocket connections.
52 You can specify the port or have QWebSocketServer pick one automatically.
53 You can listen on a specific address or on all the machine's addresses.
54 Call listen() to have the server listen for incoming connections.
56 The newConnection() signal is then emitted each time a client connects to the server.
57 Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
58 The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can
59 use for communicating with the client.
61 If an error occurs, serverError() returns the type of error, and errorString() can be called
62 to get a human readable description of what happened.
64 When listening for connections, the address and port on which the server is listening are
65 available as serverAddress() and serverPort().
67 Calling close() makes QWebSocketServer stop listening for incoming connections.
69 QWebSocketServer currently does not support
70 \l {http://tools.ietf.org/html/rfc6455#page-39} {extensions} and
71 \l {http://tools.ietf.org/html/rfc6455#page-12} {subprotocols}.
73 QWebSocketServer only supports version 13 of the WebSocket protocol, as outlined in RFC 6455.
81 \page echoserver.html example
82 \title WebSocket server example
83 \brief A sample websocket server echoing back messages sent to it.
86 The echoserver example implements a web socket server that echoes back everything that is sent
89 We start by creating a QWebSocketServer (`new QWebSocketServer()`). After the creation, we listen
90 on all local network interfaces (`QHostAddress::Any`) on the specified \a port.
91 \snippet echoserver/echoserver.cpp constructor
92 If listening is successful, we connect the `newConnection()` signal to the slot
94 The `newConnection()` signal will be thrown whenever a new web socket client is connected to our
97 \snippet echoserver/echoserver.cpp onNewConnection
98 When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`),
99 and the signals we are interested in are connected to our slots
100 (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
101 The client socket is remembered in a list, in case we would like to use it later
102 (in this example, nothing is done with it).
104 \snippet echoserver/echoserver.cpp processTextMessage
105 Whenever `processTextMessage()` is triggered, we retrieve the sender, and if valid, send back the
106 original message (`sendTextMessage()`).
107 The same is done with binary messages.
108 \snippet echoserver/echoserver.cpp processBinaryMessage
109 The only difference is that the message now is a QByteArray instead of a QString.
111 \snippet echoserver/echoserver.cpp socketDisconnected
112 Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
113 Note: it is best to use `deleteLater()` to delete the socket.
117 \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
118 This signal is emitted when accepting a new connection results in an error.
119 The \a socketError parameter describes the type of error that occurred
121 \sa pauseAccepting(), resumeAccepting()
125 \fn void QWebSocketServer::serverError(QWebSocketProtocol::CloseCode closeCode)
126 This signal is emitted when an error occurs during the setup of a web socket connection.
127 The \a closeCode parameter describes the type of error that occurred
133 \fn void QWebSocketServer::newConnection()
134 This signal is emitted every time a new connection is available.
136 \sa hasPendingConnections(), nextPendingConnection()
140 \fn void QWebSocketServer::closed()
141 This signal is emitted when the server closed it's connection.
147 \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
148 This signal is emitted when a new connection is requested.
149 The slot connected to this signal should indicate whether the origin
150 (which can be determined by the origin() call) is allowed in the \a authenticator object
151 (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()})
153 If no slot is connected to this signal, all origins will be accepted by default.
155 \note It is not possible to use a QueuedConnection to connect to
156 this signal, as the connection will always succeed.
160 \fn void QWebSocketServer::peerVerifyError(const QSslError &error)
162 QWebSocketServer can emit this signal several times during the SSL handshake,
163 before encryption has been established, to indicate that an error has
164 occurred while establishing the identity of the peer. The \a error is
165 usually an indication that QWebSocketServer is unable to securely identify the
168 This signal provides you with an early indication when something's wrong.
169 By connecting to this signal, you can manually choose to tear down the
170 connection from inside the connected slot before the handshake has
171 completed. If no action is taken, QWebSocketServer will proceed to emitting
172 QWebSocketServer::sslErrors().
178 \fn void QWebSocketServer::sslErrors(const QList<QSslError> &errors)
180 QWebSocketServer emits this signal after the SSL handshake to indicate that one
181 or more errors have occurred while establishing the identity of the
182 peer. The errors are usually an indication that QWebSocketServer is unable to
183 securely identify the peer. Unless any action is taken, the connection
184 will be dropped after this signal has been emitted.
186 \a errors contains one or more errors that prevent QSslSocket from
187 verifying the identity of the peer.
189 \sa peerVerifyError()
193 \enum QWebSocketServer::SslMode
194 Indicates whether the server operates over wss (SecureMode) or ws (NonSecureMode)
196 \value SecureMode The server operates in secure mode (over wss)
197 \value NonSecureMode The server operates in non-secure mode (over ws)
200 #include "qwebsocketprotocol.h"
201 #include "qwebsocket.h"
202 #include "qwebsocketserver.h"
203 #include "qwebsocketserver_p.h"
205 #include <QtNetwork/QTcpServer>
206 #include <QtNetwork/QTcpSocket>
207 #include <QtNetwork/QNetworkProxy>
210 #include <QtNetwork/QSslConfiguration>
216 Constructs a new QWebSocketServer with the given \a serverName.
217 The \a serverName will be used in the http handshake phase to identify the server.
218 It can be empty, in which case an empty server name will be sent to the client.
219 The \a secureMode parameter indicates whether the server operates over wss (\l{SecureMode})
220 or over ws (\l{NonSecureMode}).
222 \a parent is passed to the QObject constructor.
224 QWebSocketServer::QWebSocketServer(const QString &serverName, SslMode secureMode,
226 QObject(*(new QWebSocketServerPrivate(serverName,
228 (secureMode == SecureMode) ?
229 QWebSocketServerPrivate::SecureMode :
230 QWebSocketServerPrivate::NonSecureMode,
232 QWebSocketServerPrivate::NonSecureMode,
239 Q_D(QWebSocketServer);
244 Destroys the QWebSocketServer object. If the server is listening for connections,
245 the socket is automatically closed.
246 Any client \l{QWebSocket}s that are still queued are closed and deleted.
250 QWebSocketServer::~QWebSocketServer()
255 Closes the server. The server will no longer listen for incoming connections.
257 void QWebSocketServer::close()
259 Q_D(QWebSocketServer);
264 Returns a human readable description of the last error that occurred.
265 If no error occurred, an empty string is returned.
269 QString QWebSocketServer::errorString() const
271 Q_D(const QWebSocketServer);
272 return d->errorString();
276 Returns true if the server has pending connections; otherwise returns false.
278 \sa nextPendingConnection(), setMaxPendingConnections()
280 bool QWebSocketServer::hasPendingConnections() const
282 Q_D(const QWebSocketServer);
283 return d->hasPendingConnections();
287 Returns true if the server is currently listening for incoming connections;
288 otherwise returns false. If listening fails, error() will return the reason.
290 \sa listen(), error()
292 bool QWebSocketServer::isListening() const
294 Q_D(const QWebSocketServer);
295 return d->isListening();
299 Tells the server to listen for incoming connections on address \a address and port \a port.
300 If \a port is 0, a port is chosen automatically.
301 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
303 Returns true on success; otherwise returns false.
307 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
309 Q_D(QWebSocketServer);
310 return d->listen(address, port);
314 Returns the maximum number of pending accepted connections. The default is 30.
316 \sa setMaxPendingConnections(), hasPendingConnections()
318 int QWebSocketServer::maxPendingConnections() const
320 Q_D(const QWebSocketServer);
321 return d->maxPendingConnections();
325 Returns the next pending connection as a connected QWebSocket object.
326 QWebSocketServer does not take ownership of the returned QWebSocket object.
327 It is up to the caller to delete the object explicitly when it is done using it,
328 otherwise a memory leak will occur.
329 Q_NULLPTR is returned if this function is called when there are no pending connections.
331 Note: The returned QWebSocket object cannot be used from another thread.
333 \sa hasPendingConnections()
335 QWebSocket *QWebSocketServer::nextPendingConnection()
337 Q_D(QWebSocketServer);
338 return d->nextPendingConnection();
342 Pauses incoming new connections. Queued connections will remain in queue.
343 \sa resumeAccepting()
345 void QWebSocketServer::pauseAccepting()
347 Q_D(QWebSocketServer);
351 #ifndef QT_NO_NETWORKPROXY
353 Returns the network proxy for this server. By default QNetworkProxy::DefaultProxy is used.
357 QNetworkProxy QWebSocketServer::proxy() const
359 Q_D(const QWebSocketServer);
364 Sets the explicit network proxy for this server to \a networkProxy.
366 To disable the use of a proxy, use the QNetworkProxy::NoProxy proxy type:
369 server->setProxy(QNetworkProxy::NoProxy);
374 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
376 Q_D(QWebSocketServer);
377 d->setProxy(networkProxy);
383 Sets the SSL configuration for the QWebSocketServer to \a sslConfiguration.
384 This method has no effect if QWebSocketServer runs in non-secure mode
385 (QWebSocketServer::NonSecureMode).
387 \sa sslConfiguration(), SslMode
389 void QWebSocketServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
391 Q_D(QWebSocketServer);
392 d->setSslConfiguration(sslConfiguration);
396 Returns the SSL configuration used by the QWebSocketServer.
397 If the server is not running in secure mode (QWebSocketServer::SecureMode),
398 this method returns QSslConfiguration::defaultConfiguration().
400 \sa setSslConfiguration(), SslMode, QSslConfiguration::defaultConfiguration()
402 QSslConfiguration QWebSocketServer::sslConfiguration() const
404 Q_D(const QWebSocketServer);
405 return d->sslConfiguration();
410 Resumes accepting new connections.
413 void QWebSocketServer::resumeAccepting()
415 Q_D(QWebSocketServer);
416 d->resumeAccepting();
420 Sets the server name that will be used during the http handshake phase to the given
422 The \a serverName can be empty, in which case an empty server name will be sent to the client.
423 Existing connected clients will not be notified of this change, only newly connecting clients
424 will see this new name.
426 void QWebSocketServer::setServerName(const QString &serverName)
428 Q_D(QWebSocketServer);
429 d->setServerName(serverName);
433 Returns the server name that is used during the http handshake phase.
435 QString QWebSocketServer::serverName() const
437 Q_D(const QWebSocketServer);
438 return d->serverName();
442 Returns the server's address if the server is listening for connections; otherwise returns
445 \sa serverPort(), listen()
447 QHostAddress QWebSocketServer::serverAddress() const
449 Q_D(const QWebSocketServer);
450 return d->serverAddress();
454 Returns the secure mode the server is running in.
456 \sa QWebSocketServer(), SslMode
458 QWebSocketServer::SslMode QWebSocketServer::secureMode() const
461 Q_D(const QWebSocketServer);
462 return (d->secureMode() == QWebSocketServerPrivate::SecureMode) ?
463 QWebSocketServer::SecureMode : QWebSocketServer::NonSecureMode;
465 return QWebSocketServer::NonSecureMode;
470 Returns an error code for the last error that occurred.
471 If no error occurred, QWebSocketProtocol::CloseCodeNormal is returned.
475 QWebSocketProtocol::CloseCode QWebSocketServer::error() const
477 Q_D(const QWebSocketServer);
478 return d->serverError();
482 Returns the server's port if the server is listening for connections; otherwise returns 0.
484 \sa serverAddress(), listen()
486 quint16 QWebSocketServer::serverPort() const
488 Q_D(const QWebSocketServer);
489 return d->serverPort();
493 Sets the maximum number of pending accepted connections to \a numConnections.
494 WebSocketServer will accept no more than \a numConnections incoming connections before
495 nextPendingConnection() is called.
496 By default, the limit is 30 pending connections.
498 Clients may still able to connect after the server has reached its maximum number of
499 pending connections (i.e., QWebSocketServer can still emit the connected() signal).
500 QWebSocketServer will stop accepting the new connections, but the operating system may still
503 \sa maxPendingConnections(), hasPendingConnections()
505 void QWebSocketServer::setMaxPendingConnections(int numConnections)
507 Q_D(QWebSocketServer);
508 d->setMaxPendingConnections(numConnections);
512 Sets the socket descriptor this server should use when listening for incoming connections to
515 Returns true if the socket is set successfully; otherwise returns false.
516 The socket is assumed to be in listening state.
518 \sa socketDescriptor(), isListening()
520 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
522 Q_D(QWebSocketServer);
523 return d->setSocketDescriptor(socketDescriptor);
527 Returns the native socket descriptor the server uses to listen for incoming instructions,
528 or -1 if the server is not listening.
529 If the server is using QNetworkProxy, the returned descriptor may not be usable with
530 native socket functions.
532 \sa setSocketDescriptor(), isListening()
534 int QWebSocketServer::socketDescriptor() const
536 Q_D(const QWebSocketServer);
537 return d->socketDescriptor();
541 Returns a list of websocket versions that this server is supporting.
543 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
545 Q_D(const QWebSocketServer);
546 return d->supportedVersions();