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::newConnection()
107 This signal is emitted every time a new connection is available.
109 \sa hasPendingConnections(), nextPendingConnection()
113 \fn void QWebSocketServer::originAuthenticationRequired(QWebSocketCorsAuthenticator *authenticator)
114 This signal is emitted when a new connection is requested.
115 The slot connected to this signal should indicate whether the origin (which can be determined by the origin() call)
116 is allowed in the \a authenticator object (by issuing \l{QWebSocketCorsAuthenticator::}{setAllowed()})
118 If no slot is connected to this signal, all origins will be accepted by default.
120 \note It is not possible to use a QueuedConnection to connect to
121 this signal, as the connection will always succeed.
124 #include "qwebsocketprotocol.h"
125 #include "qwebsocket.h"
126 #include "qwebsocketserver.h"
127 #include "qwebsocketserver_p.h"
129 #include <QtNetwork/QTcpServer>
130 #include <QtNetwork/QTcpSocket>
131 #include <QtNetwork/QNetworkProxy>
136 Constructs a new WebSocketServer with the given \a serverName.
137 The \a serverName will be used in the http handshake phase to identify the server.
139 \a parent is passed to the QObject constructor.
141 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
143 d_ptr(new QWebSocketServerPrivate(serverName, this, this))
148 Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
149 Any client WebSockets that are still connected are closed and deleted.
153 QWebSocketServer::~QWebSocketServer()
159 Closes the server. The server will no longer listen for incoming connections.
161 void QWebSocketServer::close()
163 Q_D(QWebSocketServer);
168 Returns a human readable description of the last error that occurred.
172 QString QWebSocketServer::errorString() const
174 Q_D(const QWebSocketServer);
175 return d->errorString();
179 Returns true if the server has pending connections; otherwise returns false.
181 \sa nextPendingConnection(), setMaxPendingConnections()
183 bool QWebSocketServer::hasPendingConnections() const
185 Q_D(const QWebSocketServer);
186 return d->hasPendingConnections();
190 Returns true if the server is currently listening for incoming connections; otherwise returns false.
194 bool QWebSocketServer::isListening() const
196 Q_D(const QWebSocketServer);
197 return d->isListening();
201 Tells the server to listen for incoming connections on address \a address and port \a port.
202 If \a port is 0, a port is chosen automatically.
203 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
205 Returns true on success; otherwise returns false.
209 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
211 Q_D(QWebSocketServer);
212 return d->listen(address, port);
216 Returns the maximum number of pending accepted connections. The default is 30.
218 \sa setMaxPendingConnections(), hasPendingConnections()
220 int QWebSocketServer::maxPendingConnections() const
222 Q_D(const QWebSocketServer);
223 return d->maxPendingConnections();
227 Returns the next pending connection as a connected WebSocket object.
228 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.
229 0 is returned if this function is called when there are no pending connections.
231 Note: The returned WebSocket object cannot be used from another thread..
233 \sa hasPendingConnections()
235 QWebSocket *QWebSocketServer::nextPendingConnection()
237 Q_D(QWebSocketServer);
238 return d->nextPendingConnection();
242 Pauses incoming new connections. Queued connections will remain in queue.
243 \sa resumeAccepting()
245 void QWebSocketServer::pauseAccepting()
247 Q_D(QWebSocketServer);
251 #ifndef QT_NO_NETWORKPROXY
253 Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
257 QNetworkProxy QWebSocketServer::proxy() const
259 Q_D(const QWebSocketServer);
264 \brief Sets the explicit network proxy for this socket to \a networkProxy.
266 To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
269 server->setProxy(QNetworkProxy::NoProxy);
274 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
276 Q_D(QWebSocketServer);
277 d->setProxy(networkProxy);
281 Resumes accepting new connections.
284 void QWebSocketServer::resumeAccepting()
286 Q_D(QWebSocketServer);
287 d->resumeAccepting();
291 Sets the server name that will be used during the http handshake phase to the given \a serverName.
292 Existing connected clients will not be notified of this change, only newly connecting clients
293 will see this new name.
295 void QWebSocketServer::setServerName(const QString &serverName)
297 Q_D(QWebSocketServer);
298 d->setServerName(serverName);
302 Returns the server name that is used during the http handshake phase.
304 QString QWebSocketServer::serverName() const
306 Q_D(const QWebSocketServer);
307 return d->serverName();
311 Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
313 \sa serverPort(), listen()
315 QHostAddress QWebSocketServer::serverAddress() const
317 Q_D(const QWebSocketServer);
318 return d->serverAddress();
322 Returns an error code for the last error that occurred.
325 QAbstractSocket::SocketError QWebSocketServer::serverError() const
327 Q_D(const QWebSocketServer);
328 return d->serverError();
332 Returns the server's port if the server is listening for connections; otherwise returns 0.
333 \sa serverAddress(), listen()
335 quint16 QWebSocketServer::serverPort() const
337 Q_D(const QWebSocketServer);
338 return d->serverPort();
342 Sets the maximum number of pending accepted connections to \a numConnections.
343 WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
344 By default, the limit is 30 pending connections.
346 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.
347 \sa maxPendingConnections(), hasPendingConnections()
349 void QWebSocketServer::setMaxPendingConnections(int numConnections)
351 Q_D(QWebSocketServer);
352 d->setMaxPendingConnections(numConnections);
356 Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
358 Returns true if the socket is set successfully; otherwise returns false.
359 The socket is assumed to be in listening state.
361 \sa socketDescriptor(), isListening()
363 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
365 Q_D(QWebSocketServer);
366 return d->setSocketDescriptor(socketDescriptor);
370 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
371 If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
373 \sa setSocketDescriptor(), isListening()
375 int QWebSocketServer::socketDescriptor() const
377 Q_D(const QWebSocketServer);
378 return d->socketDescriptor();
382 Waits for at most \a msec milliseconds or until an incoming connection is available.
383 Returns true if a connection is available; otherwise returns false.
384 If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
386 \note This is a blocking function call.
387 \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.
388 \note The non-blocking alternative is to connect to the newConnection() signal.
390 If \a msec is -1, this function will not time out.
392 \sa hasPendingConnections(), nextPendingConnection()
394 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
396 Q_D(QWebSocketServer);
397 return d->waitForNewConnection(msec, timedOut);
401 Returns a list of websocket versions that this server is supporting.
403 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
405 Q_D(const QWebSocketServer);
406 return d->supportedVersions();
410 Returns a list of websocket subprotocols that this server supports.
412 QList<QString> QWebSocketServer::supportedProtocols() const
414 Q_D(const QWebSocketServer);
415 return d->supportedProtocols();
419 Returns a list of websocket extensions that this server supports.
421 QList<QString> QWebSocketServer::supportedExtensions() const
423 Q_D(const QWebSocketServer);
424 return d->supportedExtensions();