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()
92 #include <QNetworkProxy>
93 #include "qwebsocketprotocol.h"
94 #include "qwebsocket.h"
95 #include "qwebsocketserver.h"
96 #include "qwebsocketserver_p.h"
101 Constructs a new WebSocketServer with the given \a serverName.
102 The \a serverName will be used in the http handshake phase to identify the server.
104 \a parent is passed to the QObject constructor.
106 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
108 d_ptr(new QWebSocketServerPrivate(serverName, this, this))
113 Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
114 Any client WebSockets that are still connected are closed and deleted.
118 QWebSocketServer::~QWebSocketServer()
124 Closes the server. The server will no longer listen for incoming connections.
126 void QWebSocketServer::close()
132 Returns a human readable description of the last error that occurred.
136 QString QWebSocketServer::errorString() const
138 return d_ptr->errorString();
142 Returns true if the server has pending connections; otherwise returns false.
144 \sa nextPendingConnection(), setMaxPendingConnections()
146 bool QWebSocketServer::hasPendingConnections() const
148 return d_ptr->hasPendingConnections();
152 Returns true if the server is currently listening for incoming connections; otherwise returns false.
156 bool QWebSocketServer::isListening() const
158 return d_ptr->isListening();
162 Tells the server to listen for incoming connections on address \a address and port \a port.
163 If \a port is 0, a port is chosen automatically.
164 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
166 Returns true on success; otherwise returns false.
170 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
172 return d_ptr->listen(address, port);
176 Returns the maximum number of pending accepted connections. The default is 30.
178 \sa setMaxPendingConnections(), hasPendingConnections()
180 int QWebSocketServer::maxPendingConnections() const
182 return d_ptr->maxPendingConnections();
186 Returns the next pending connection as a connected WebSocket object.
187 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.
188 0 is returned if this function is called when there are no pending connections.
190 Note: The returned WebSocket object cannot be used from another thread..
192 \sa hasPendingConnections()
194 QWebSocket *QWebSocketServer::nextPendingConnection()
196 return d_ptr->nextPendingConnection();
200 Pauses incoming new connections. Queued connections will remain in queue.
201 \sa resumeAccepting()
203 void QWebSocketServer::pauseAccepting()
205 d_ptr->pauseAccepting();
208 #ifndef QT_NO_NETWORKPROXY
210 Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
214 QNetworkProxy QWebSocketServer::proxy() const
216 return d_ptr->proxy();
220 \brief Sets the explicit network proxy for this socket to \a networkProxy.
222 To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
225 server->setProxy(QNetworkProxy::NoProxy);
230 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
232 d_ptr->setProxy(networkProxy);
236 Resumes accepting new connections.
239 void QWebSocketServer::resumeAccepting()
241 d_ptr->resumeAccepting();
245 Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
247 \sa serverPort(), listen()
249 QHostAddress QWebSocketServer::serverAddress() const
251 return d_ptr->serverAddress();
255 Returns an error code for the last error that occurred.
258 QAbstractSocket::SocketError QWebSocketServer::serverError() const
260 return d_ptr->serverError();
264 Returns the server's port if the server is listening for connections; otherwise returns 0.
265 \sa serverAddress(), listen()
267 quint16 QWebSocketServer::serverPort() const
269 return d_ptr->serverPort();
273 Sets the maximum number of pending accepted connections to \a numConnections.
274 WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.
275 By default, the limit is 30 pending connections.
277 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.
278 \sa maxPendingConnections(), hasPendingConnections()
280 void QWebSocketServer::setMaxPendingConnections(int numConnections)
282 d_ptr->setMaxPendingConnections(numConnections);
286 Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
288 Returns true if the socket is set successfully; otherwise returns false.
289 The socket is assumed to be in listening state.
291 \sa socketDescriptor(), isListening()
293 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
295 return d_ptr->setSocketDescriptor(socketDescriptor);
299 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
300 If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
302 \sa setSocketDescriptor(), isListening()
304 int QWebSocketServer::socketDescriptor() const
306 return d_ptr->socketDescriptor();
310 Waits for at most \a msec milliseconds or until an incoming connection is available.
311 Returns true if a connection is available; otherwise returns false.
312 If the operation timed out and \a timedOut is not 0, \a timedOut will be set to true.
314 \note This is a blocking function call.
315 \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.
316 \note The non-blocking alternative is to connect to the newConnection() signal.
318 If \a msec is -1, this function will not time out.
320 \sa hasPendingConnections(), nextPendingConnection()
322 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
324 return d_ptr->waitForNewConnection(msec, timedOut);
328 Returns a list of websocket versions that this server is supporting.
330 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
332 return d_ptr->supportedVersions();
336 Returns a list of websocket subprotocols that this server supports.
338 QList<QString> QWebSocketServer::supportedProtocols() const
340 return d_ptr->supportedProtocols();
344 Returns a list of websocket extensions that this server supports.
346 QList<QString> QWebSocketServer::supportedExtensions() const
348 return d_ptr->supportedExtensions();
352 This method checks if the given \a origin is allowed; it returns true when the \a origin is allowed, otherwise false.
353 It is supposed to be overriden by a subclass to filter out unwanted origins.
354 By default, every origin is accepted.
356 \note Checking on the origin does not make much sense when the server is accessed
357 via a non-browser client, as that client can set whatever origin header it likes
358 In case of a browser client, the server SHOULD check the validity of the origin.
359 \sa http://tools.ietf.org/html/rfc6455#section-10
361 bool QWebSocketServer::isOriginAllowed(const QString &origin) const