2 QWebSockets implements the WebSocket protocol as defined in RFC 6455.
3 Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 \class QWebSocketServer
25 \brief Implements a websocket-based server.
27 It is modeled after QTcpServer, and behaves the same. So, if you know how to use QTcpServer, you know how to use QWebSocketServer.
28 This class makes it possible to accept incoming websocket connections.
29 You can specify the port or have QWebSocketServer pick one automatically.
30 You can listen on a specific address or on all the machine's addresses.
31 Call listen() to have the server listen for incoming connections.
33 The newConnection() signal is then emitted each time a client connects to the server.
34 Call nextPendingConnection() to accept the pending connection as a connected QWebSocket.
35 The function returns a pointer to a QWebSocket in QAbstractSocket::ConnectedState that you can use for communicating with the client.
36 If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.
37 When listening for connections, the address and port on which the server is listening are available as serverAddress() and serverPort().
38 Calling close() makes QWebSocketServer stop listening for incoming connections.
39 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.
47 \page echoserver.html example
48 \title WebSocket server example
49 \brief A sample websocket server echoing back messages sent to it.
52 The echoserver example implements a web socket server that echoes back everything that is sent to it.
54 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.
55 \snippet echoserver.cpp constructor
56 If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`.
57 The `newConnection()` signal will be thrown whenever a new web socket client is connected to our server.
59 \snippet echoserver.cpp onNewConnection
60 When a new connection is received, the client QWebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in
61 are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
62 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).
64 \snippet echoserver.cpp processMessage
65 Whenever `processMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`send()`).
66 The same is done with binary messages.
67 \snippet echoserver.cpp processBinaryMessage
68 The only difference is that the message now is a QByteArray instead of a QString.
70 \snippet echoserver.cpp socketDisconnected
71 Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
72 Note: it is best to use `deleteLater()` to delete the socket.
76 \fn void QWebSocketServer::acceptError(QAbstractSocket::SocketError socketError)
77 This signal is emitted when accepting a new connection results in an error.
78 The \a socketError parameter describes the type of error that occurred
80 \sa pauseAccepting(), resumeAccepting()
84 \fn void QWebSocketServer::newConnection()
85 This signal is emitted every time a new connection is available.
87 \sa hasPendingConnections(), nextPendingConnection()
91 \fn void QWebSocketServer::originAuthenticationRequired(QCorsAuthenticator *authenticator)
92 This signal is emitted when a new connection is requested.
93 The slot connected to this signal should indicate whether the origin (which can be determined by the origin() call)
94 is allowed in the \a authenticator object (by issuing \l{QCorsAuthenticator::}{setAllowed()})
96 If no slot is connected to this signal, all origins will be accepted by default.
98 \note It is not possible to use a QueuedConnection to connect to
99 this signal, as the connection will always succeed.
102 #include <QTcpServer>
103 #include <QTcpSocket>
104 #include <QNetworkProxy>
105 #include "qwebsocketprotocol.h"
106 #include "qwebsocket.h"
107 #include "qwebsocketserver.h"
108 #include "qwebsocketserver_p.h"
110 //TODO: CorsCheck: give list in constructor or use CorsAuthenticator object
111 //in QNetworkAccessManager the signal cannot be connected to a queued signal, because it waits for the signal to return
116 Constructs a new WebSocketServer with the given \a serverName.
117 The \a serverName will be used in the http handshake phase to identify the server.
119 \a parent is passed to the QObject constructor.
121 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
123 d_ptr(new QWebSocketServerPrivate(serverName, this, this))
128 Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
129 Any client WebSockets that are still connected are closed and deleted.
133 QWebSocketServer::~QWebSocketServer()
139 Closes the server. The server will no longer listen for incoming connections.
141 void QWebSocketServer::close()
143 Q_D(QWebSocketServer);
148 Returns a human readable description of the last error that occurred.
152 QString QWebSocketServer::errorString() const
154 Q_D(const QWebSocketServer);
155 return d->errorString();
159 Returns true if the server has pending connections; otherwise returns false.
161 \sa nextPendingConnection(), setMaxPendingConnections()
163 bool QWebSocketServer::hasPendingConnections() const
165 Q_D(const QWebSocketServer);
166 return d->hasPendingConnections();
170 Returns true if the server is currently listening for incoming connections; otherwise returns false.
174 bool QWebSocketServer::isListening() const
176 Q_D(const QWebSocketServer);
177 return d->isListening();
181 Tells the server to listen for incoming connections on address \a address and port \a port.
182 If \a port is 0, a port is chosen automatically.
183 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
185 Returns true on success; otherwise returns false.
189 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
191 Q_D(QWebSocketServer);
192 return d->listen(address, port);
196 Returns the maximum number of pending accepted connections. The default is 30.
198 \sa setMaxPendingConnections(), hasPendingConnections()
200 int QWebSocketServer::maxPendingConnections() const
202 Q_D(const QWebSocketServer);
203 return d->maxPendingConnections();
207 Returns the next pending connection as a connected WebSocket object.
208 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.
209 0 is returned if this function is called when there are no pending connections.
211 Note: The returned WebSocket object cannot be used from another thread..
213 \sa hasPendingConnections()
215 QWebSocket *QWebSocketServer::nextPendingConnection()
217 Q_D(QWebSocketServer);
218 return d->nextPendingConnection();
222 Pauses incoming new connections. Queued connections will remain in queue.
223 \sa resumeAccepting()
225 void QWebSocketServer::pauseAccepting()
227 Q_D(QWebSocketServer);
231 #ifndef QT_NO_NETWORKPROXY
233 Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
237 QNetworkProxy QWebSocketServer::proxy() const
239 Q_D(const QWebSocketServer);
244 \brief Sets the explicit network proxy for this socket to \a networkProxy.
246 To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
249 server->setProxy(QNetworkProxy::NoProxy);
254 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
256 Q_D(QWebSocketServer);
257 d->setProxy(networkProxy);
261 Resumes accepting new connections.
264 void QWebSocketServer::resumeAccepting()
266 Q_D(QWebSocketServer);
267 d->resumeAccepting();
271 Sets the server name that will be used during the http handshake phase to the given \a serverName.
272 Existing connected clients will not be notified of this change, only newly connecting clients
273 will see this new name.
275 void QWebSocketServer::setServerName(const QString &serverName)
277 Q_D(QWebSocketServer);
278 d->setServerName(serverName);
282 Returns the server name that is used during the http handshake phase.
284 QString QWebSocketServer::serverName() const
286 Q_D(const QWebSocketServer);
287 return d->serverName();
291 Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
293 \sa serverPort(), listen()
295 QHostAddress QWebSocketServer::serverAddress() const
297 Q_D(const QWebSocketServer);
298 return d->serverAddress();
302 Returns an error code for the last error that occurred.
305 QAbstractSocket::SocketError QWebSocketServer::serverError() const
307 Q_D(const QWebSocketServer);
308 return d->serverError();
312 Returns the server's port if the server is listening for connections; otherwise returns 0.
313 \sa serverAddress(), listen()
315 quint16 QWebSocketServer::serverPort() const
317 Q_D(const QWebSocketServer);
318 return d->serverPort();
322 Sets the maximum number of pending accepted connections to \a numConnections.
323 WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
324 By default, the limit is 30 pending connections.
326 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.
327 \sa maxPendingConnections(), hasPendingConnections()
329 void QWebSocketServer::setMaxPendingConnections(int numConnections)
331 Q_D(QWebSocketServer);
332 d->setMaxPendingConnections(numConnections);
336 Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
338 Returns true if the socket is set successfully; otherwise returns false.
339 The socket is assumed to be in listening state.
341 \sa socketDescriptor(), isListening()
343 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
345 Q_D(QWebSocketServer);
346 return d->setSocketDescriptor(socketDescriptor);
350 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
351 If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
353 \sa setSocketDescriptor(), isListening()
355 int QWebSocketServer::socketDescriptor() const
357 Q_D(const QWebSocketServer);
358 return d->socketDescriptor();
362 Waits for at most \a msec milliseconds or until an incoming connection is available.
363 Returns true if a connection is available; otherwise returns false.
364 If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
366 \note This is a blocking function call.
367 \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.
368 \note The non-blocking alternative is to connect to the newConnection() signal.
370 If \a msec is -1, this function will not time out.
372 \sa hasPendingConnections(), nextPendingConnection()
374 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
376 Q_D(QWebSocketServer);
377 return d->waitForNewConnection(msec, timedOut);
381 Returns a list of websocket versions that this server is supporting.
383 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
385 Q_D(const QWebSocketServer);
386 return d->supportedVersions();
390 Returns a list of websocket subprotocols that this server supports.
392 QList<QString> QWebSocketServer::supportedProtocols() const
394 Q_D(const QWebSocketServer);
395 return d->supportedProtocols();
399 Returns a list of websocket extensions that this server supports.
401 QList<QString> QWebSocketServer::supportedExtensions() const
403 Q_D(const QWebSocketServer);
404 return d->supportedExtensions();