1 /****************************************************************************
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
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, you know how to use QWebSocketServer.
50 This class makes it possible to accept incoming websocket connections.
51 You can specify the port or have QWebSocketServer pick one automatically.
52 You can listen on a specific address or on all the machine's addresses.
53 Call listen() to have the server listen for incoming connections.
55 The newConnection() signal is then emitted each time a client connects to the server.
56 Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
57 The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can use for communicating with the client.
58 If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
59 When listening for connections, the address and port on which the server is listening are available as serverAddress() and serverPort().
60 Calling close() makes QWebSocketServer stop listening for incoming connections.
61 Although QWebSocketServer is mostly designed for use with an event loop, it's possible to use it without one. In that case, you must use waitForNewConnection(), which blocks until either a connection is available or a timeout expires.
69 \page echoserver.html example
70 \title WebSocket server example
71 \brief A sample websocket server echoing back messages sent to it.
74 The echoserver example implements a web socket server that echoes back everything that is sent to it.
76 We start by creating a QWebSocketServer (`new QWebSocketServer()`). After the creation, we listen on all local network interfaces (`QHostAddress::Any`) on the specified \a port.
77 \snippet echoserver/echoserver.cpp constructor
78 If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`.
79 The `newConnection()` signal will be thrown whenever a new web socket client is connected to our server.
81 \snippet echoserver/echoserver.cpp onNewConnection
82 When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in
83 are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
84 The client socket is remembered in a list, in case we would like to use it later (in this example, nothing is done with it).
86 \snippet echoserver/echoserver.cpp processMessage
87 Whenever `processMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`send()`).
88 The same is done with binary messages.
89 \snippet echoserver/echoserver.cpp processBinaryMessage
90 The only difference is that the message now is a QByteArray instead of a QString.
92 \snippet echoserver/echoserver.cpp socketDisconnected
93 Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
94 Note: it is best to use `deleteLater()` to delete the socket.
98 \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
99 This signal is emitted when accepting a new connection results in an error.
100 The \a socketError parameter describes the type of error that occurred
102 \sa pauseAccepting(), resumeAccepting()
106 \fn void QWebSocketServer::serverError(QNetworkProtocol::CloseCode closeCode)
107 This signal is emitted when an error occurs during the setup of a web socket connection.
108 The \a closeCode parameter describes the type of error that occurred
114 \fn void QWebSocketServer::newConnection()
115 This signal is emitted every time a new connection is available.
117 \sa hasPendingConnections(), nextPendingConnection()
121 \fn void QWebSocketServer::closed()
122 This signal is emitted when the server closed it's connection.
128 \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
129 This signal is emitted when a new connection is requested.
130 The slot connected to this signal should indicate whether the origin (which can be determined by the origin() call)
131 is allowed in the \a authenticator object (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()})
133 If no slot is connected to this signal, all origins will be accepted by default.
135 \note It is not possible to use a QueuedConnection to connect to
136 this signal, as the connection will always succeed.
139 #include "qwebsocketprotocol.h"
140 #include "qwebsocket.h"
141 #include "qwebsocketserver.h"
142 #include "qwebsocketserver_p.h"
144 #include <QtNetwork/QTcpServer>
145 #include <QtNetwork/QTcpSocket>
146 #include <QtNetwork/QNetworkProxy>
149 #include <QtNetwork/QSslConfiguration>
155 Constructs a new WebSocketServer with the given \a serverName.
156 The \a serverName will be used in the http handshake phase to identify the server.
159 \a parent is passed to the QObject constructor.
161 QWebSocketServer::QWebSocketServer(const QString &serverName, SecureMode secureMode, QObject *parent) :
163 d_ptr(new QWebSocketServerPrivate(serverName,
165 (secureMode == SECURE_MODE) ? QWebSocketServerPrivate::SECURE_MODE : QWebSocketServerPrivate::NON_SECURE_MODE,
167 QWebSocketServerPrivate::NON_SECURE_MODE,
178 Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
179 Any client WebSockets that are still connected are closed and deleted.
183 QWebSocketServer::~QWebSocketServer()
189 Closes the server. The server will no longer listen for incoming connections.
191 void QWebSocketServer::close()
193 Q_D(QWebSocketServer);
198 Returns a human readable description of the last error that occurred.
202 QString QWebSocketServer::errorString() const
204 Q_D(const QWebSocketServer);
205 return d->errorString();
209 Returns true if the server has pending connections; otherwise returns false.
211 \sa nextPendingConnection(), setMaxPendingConnections()
213 bool QWebSocketServer::hasPendingConnections() const
215 Q_D(const QWebSocketServer);
216 return d->hasPendingConnections();
220 Returns true if the server is currently listening for incoming connections; otherwise returns false.
224 bool QWebSocketServer::isListening() const
226 Q_D(const QWebSocketServer);
227 return d->isListening();
231 Tells the server to listen for incoming connections on address \a address and port \a port.
232 If \a port is 0, a port is chosen automatically.
233 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
235 Returns true on success; otherwise returns false.
239 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
241 Q_D(QWebSocketServer);
242 return d->listen(address, port);
246 Returns the maximum number of pending accepted connections. The default is 30.
248 \sa setMaxPendingConnections(), hasPendingConnections()
250 int QWebSocketServer::maxPendingConnections() const
252 Q_D(const QWebSocketServer);
253 return d->maxPendingConnections();
257 Returns the next pending connection as a connected WebSocket object.
258 The socket is created as a child of the server, which means that it is automatically deleted when the WebSocketServer object is destroyed. It is still a good idea to delete the object explicitly when you are done with it, to avoid wasting memory.
259 0 is returned if this function is called when there are no pending connections.
261 Note: The returned WebSocket object cannot be used from another thread..
263 \sa hasPendingConnections()
265 QWebSocket *QWebSocketServer::nextPendingConnection()
267 Q_D(QWebSocketServer);
268 return d->nextPendingConnection();
272 Pauses incoming new connections. Queued connections will remain in queue.
273 \sa resumeAccepting()
275 void QWebSocketServer::pauseAccepting()
277 Q_D(QWebSocketServer);
281 #ifndef QT_NO_NETWORKPROXY
283 Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
287 QNetworkProxy QWebSocketServer::proxy() const
289 Q_D(const QWebSocketServer);
294 \brief Sets the explicit network proxy for this socket to \a networkProxy.
296 To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
299 server->setProxy(QNetworkProxy::NoProxy);
304 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
306 Q_D(QWebSocketServer);
307 d->setProxy(networkProxy);
313 Sets the SSL configuration for the websocket server to \a sslConfiguration.
314 This method has no effect if QWebSocketServer runs in non-secure mode (QWebSocketServer::NON_SECURE_MODE).
316 \sa sslConfiguration(), SecureMode
318 void QWebSocketServer::setSslConfiguration(const QSslConfiguration &sslConfiguration)
320 Q_D(QWebSocketServer);
321 d->setSslConfiguration(sslConfiguration);
325 Returns the SSL configuration used by the websocket server.
326 If the server is not running in secure mode (QWebSocketServer::SECURE_MODE),
327 this method returns QSslConfiguration::defaultConfiguration().
329 \sa sslConfiguration(), SecureMode, QSslConfiguration::defaultConfiguration()
331 QSslConfiguration QWebSocketServer::sslConfiguration() const
333 Q_D(const QWebSocketServer);
334 return d->sslConfiguration();
339 Resumes accepting new connections.
342 void QWebSocketServer::resumeAccepting()
344 Q_D(QWebSocketServer);
345 d->resumeAccepting();
349 Sets the server name that will be used during the http handshake phase to the given \a serverName.
350 Existing connected clients will not be notified of this change, only newly connecting clients
351 will see this new name.
353 void QWebSocketServer::setServerName(const QString &serverName)
355 Q_D(QWebSocketServer);
356 d->setServerName(serverName);
360 Returns the server name that is used during the http handshake phase.
362 QString QWebSocketServer::serverName() const
364 Q_D(const QWebSocketServer);
365 return d->serverName();
369 Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
371 \sa serverPort(), listen()
373 QHostAddress QWebSocketServer::serverAddress() const
375 Q_D(const QWebSocketServer);
376 return d->serverAddress();
380 Returns the mode the server is running in.
382 \sa QWebSocketServer(), SecureMode
384 QWebSocketServer::SecureMode QWebSocketServer::secureMode() const
386 Q_D(const QWebSocketServer);
388 return (d->secureMode() == QWebSocketServerPrivate::SECURE_MODE) ?
389 QWebSocketServer::SECURE_MODE : QWebSocketServer::NON_SECURE_MODE;
391 return QWebSocketServer::NON_SECURE_MODE;
396 Returns an error code for the last error that occurred.
399 QWebSocketProtocol::CloseCode QWebSocketServer::error() const
401 Q_D(const QWebSocketServer);
402 return d->serverError();
406 Returns the server's port if the server is listening for connections; otherwise returns 0.
407 \sa serverAddress(), listen()
409 quint16 QWebSocketServer::serverPort() const
411 Q_D(const QWebSocketServer);
412 return d->serverPort();
416 Sets the maximum number of pending accepted connections to \a numConnections.
417 WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
418 By default, the limit is 30 pending connections.
420 Clients may still able to connect after the server has reached its maximum number of pending connections (i.e., WebSocket can still emit the connected() signal). WebSocketServer will stop accepting the new connections, but the operating system may still keep them in queue.
421 \sa maxPendingConnections(), hasPendingConnections()
423 void QWebSocketServer::setMaxPendingConnections(int numConnections)
425 Q_D(QWebSocketServer);
426 d->setMaxPendingConnections(numConnections);
430 Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
432 Returns true if the socket is set successfully; otherwise returns false.
433 The socket is assumed to be in listening state.
435 \sa socketDescriptor(), isListening()
437 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
439 Q_D(QWebSocketServer);
440 return d->setSocketDescriptor(socketDescriptor);
444 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
445 If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
447 \sa setSocketDescriptor(), isListening()
449 int QWebSocketServer::socketDescriptor() const
451 Q_D(const QWebSocketServer);
452 return d->socketDescriptor();
456 Waits for at most \a msec milliseconds or until an incoming connection is available.
457 Returns true if a connection is available; otherwise returns false.
458 If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
460 \note This is a blocking function call.
461 \note Its use is disadvised in a single-threaded GUI application, since the whole application will stop responding until the function returns. waitForNewConnection() is mostly useful when there is no event loop available.
462 \note The non-blocking alternative is to connect to the newConnection() signal.
464 If \a msec is -1, this function will not time out.
466 \sa hasPendingConnections(), nextPendingConnection()
468 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
470 Q_D(QWebSocketServer);
471 return d->waitForNewConnection(msec, timedOut);
475 Returns a list of websocket versions that this server is supporting.
477 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
479 Q_D(const QWebSocketServer);
480 return d->supportedVersions();
484 Returns a list of websocket subprotocols that this server supports.
486 QStringList QWebSocketServer::supportedProtocols() const
488 Q_D(const QWebSocketServer);
489 return d->supportedProtocols();
493 Returns a list of websocket extensions that this server supports.
495 QStringList QWebSocketServer::supportedExtensions() const
497 Q_D(const QWebSocketServer);
498 return d->supportedExtensions();