4 The WebSocketServer class provides a websocket-based server.
5 It is modeled after QTcpServer, and behaves the same. So, if you know how to use QTcpServer, you know how to use WebSocketServer.\n
6 This class makes it possible to accept incoming websocket connections.\n
7 You can specify the port or have WebSocketServer pick one automatically.\n
8 You can listen on a specific address or on all the machine's addresses.\n
9 Call listen() to have the server listen for incoming connections.\n
11 The newConnection() signal is then emitted each time a client connects to the server.\n
12 Call nextPendingConnection() to accept the pending connection as a connected WebSocket.
13 The function returns a pointer to a WebSocket in QAbstractSocket::ConnectedState that you can use for communicating with the client.\n
14 If an error occurs, serverError() returns the type of error, and errorString() can be called to get a human readable description of what happened.\n
15 When listening for connections, the address and port on which the server is listening are available as serverAddress() and serverPort().\n
16 Calling close() makes WebSocketServer stop listening for incoming connections.\n
17 Although WebSocketServer 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.
21 \author Kurt Pattyn (pattyn.kurt@gmail.com)
27 \page echoserver WebSocket server example
28 \brief A sample websocket server echoing back messages sent to it.
31 The echoserver example implements a web socket server that echoes back everything that is sent to it.
33 We start by creating a WebSocketServer (`new WebSocketServer()`). After the creation, we listen on all local network interfaces (`QHostAddress::Any`) on the specified \a port.
34 \snippet echoserver.cpp constructor
35 If listening is successful, we connect the `newConnection()` signal to the slot `onNewConnection()`.
36 The `newConnection()` signal will be thrown whenever a new web socket client is connected to our server.
38 \snippet echoserver.cpp onNewConnection
39 When a new connection is received, the client WebSocket is retrieved (`nextPendingConnection()`), and the signals we are interested in
40 are connected to our slots (`textMessageReceived()`, `binaryMessageReceived()` and `disconnected()`).
41 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).
43 \snippet echoserver.cpp processMessage
44 Whenever `processMessage()` is triggered, we retrieve the sender, and if valid, send back the original message (`send()`).
45 The same is done with binary messages.
46 \snippet echoserver.cpp processBinaryMessage
47 The only difference is that the message now is a QByteArray instead of a QString.
49 \snippet echoserver.cpp socketDisconnected
50 Whenever a socket is disconnected, we remove it from the clients list and delete the socket.
51 Note: it is best to use `deleteLater()` to delete the socket.
55 \fn void WebSocketServer::newConnection()
56 This signal is emitted every time a new connection is available.
58 \sa hasPendingConnections() and nextPendingConnection().
63 #include <QNetworkProxy>
64 #include "qwebsocketprotocol.h"
65 #include "qwebsocket.h"
66 #include "qwebsocketserver.h"
67 #include "qwebsocketserver_p.h"
72 Constructs a new WebSocketServer.
74 \a parent is passed to the QObject constructor.
76 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
78 d_ptr(new QWebSocketServerPrivate(serverName, this, this))
83 Destroys the WebSocketServer object. If the server is listening for connections, the socket is automatically closed.
84 Any client WebSockets that are still connected are closed and deleted.
88 QWebSocketServer::~QWebSocketServer()
94 Closes the server. The server will no longer listen for incoming connections.
96 void QWebSocketServer::close()
102 Returns a human readable description of the last error that occurred.
106 QString QWebSocketServer::errorString() const
108 return d_ptr->errorString();
112 Returns true if the server has pending connections; otherwise returns false.
114 \sa nextPendingConnection() and setMaxPendingConnections().
116 bool QWebSocketServer::hasPendingConnections() const
118 return d_ptr->hasPendingConnections();
122 Returns true if the server is currently listening for incoming connections; otherwise returns false.
126 bool QWebSocketServer::isListening() const
128 return d_ptr->isListening();
132 Tells the server to listen for incoming connections on address \a address and port \a port.
133 If \a port is 0, a port is chosen automatically.\n
134 If \a address is QHostAddress::Any, the server will listen on all network interfaces.
136 Returns true on success; otherwise returns false.
140 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
142 return d_ptr->listen(address, port);
146 Returns the maximum number of pending accepted connections. The default is 30.
148 \sa setMaxPendingConnections() and hasPendingConnections().
150 int QWebSocketServer::maxPendingConnections() const
152 return d_ptr->maxPendingConnections();
156 Returns the next pending connection as a connected WebSocket object.
157 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.
158 0 is returned if this function is called when there are no pending connections.
160 Note: The returned WebSocket object cannot be used from another thread..
162 \sa hasPendingConnections().
164 QWebSocket *QWebSocketServer::nextPendingConnection()
166 return d_ptr->nextPendingConnection();
170 #ifndef QT_NO_NETWORKPROXY
172 Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
176 QNetworkProxy QWebSocketServer::proxy() const
178 return d_ptr->proxy();
182 \brief Sets the explicit network proxy for this socket to \a networkProxy.
184 To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
187 server->setProxy(QNetworkProxy::NoProxy);
192 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
194 d_ptr->setProxy(networkProxy);
197 Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
199 \sa serverPort() and listen().
201 QHostAddress QWebSocketServer::serverAddress() const
203 return d_ptr->serverAddress();
207 Returns an error code for the last error that occurred.
210 QAbstractSocket::SocketError QWebSocketServer::serverError() const
212 return d_ptr->serverError();
216 Returns the server's port if the server is listening for connections; otherwise returns 0.
217 \sa serverAddress() and listen().
219 quint16 QWebSocketServer::serverPort() const
221 return d_ptr->serverPort();
225 Sets the maximum number of pending accepted connections to \a numConnections.
226 WebSocketServer will accept no more than \a numConnections incoming connections before nextPendingConnection() is called.\n
227 By default, the limit is 30 pending connections.
229 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.
230 \sa maxPendingConnections() and hasPendingConnections().
232 void QWebSocketServer::setMaxPendingConnections(int numConnections)
234 d_ptr->setMaxPendingConnections(numConnections);
238 Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
240 Returns true if the socket is set successfully; otherwise returns false.\n
241 The socket is assumed to be in listening state.
243 \sa socketDescriptor() and isListening().
245 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
247 return d_ptr->setSocketDescriptor(socketDescriptor);
251 Returns the native socket descriptor the server uses to listen for incoming instructions, or -1 if the server is not listening.
252 If the server is using QNetworkProxy, the returned descriptor may not be usable with native socket functions.
254 \sa setSocketDescriptor() and isListening().
256 int QWebSocketServer::socketDescriptor() const
258 return d_ptr->socketDescriptor();
262 Waits for at most \a msec milliseconds or until an incoming connection is available.
263 Returns true if a connection is available; otherwise returns false.
264 If the operation timed out and \a timedOut is not 0, \a *timedOut will be set to true.
266 \note This is a blocking function call.
267 \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.
268 \note The non-blocking alternative is to connect to the newConnection() signal.
270 If \a msec is -1, this function will not time out.
272 \sa hasPendingConnections() and nextPendingConnection().
274 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
276 return d_ptr->waitForNewConnection(msec, timedOut);
280 Returns a list of websocket versions that this server is supporting.
282 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
284 return d_ptr->supportedVersions();
288 Returns a list of websocket subprotocols that this server supports.
290 QList<QString> QWebSocketServer::supportedProtocols() const
292 return d_ptr->supportedProtocols();
296 Returns a list of websocket extensions that this server supports.
298 QList<QString> QWebSocketServer::supportedExtensions() const
300 return d_ptr->supportedExtensions();
303 //Checking on the origin does not make much sense when the server is accessed
304 //via a non-browser client, as that client can set whatever origin header it likes
305 //In case of a browser client, the server SHOULD check the validity of the origin
306 //see http://tools.ietf.org/html/rfc6455#section-10
307 bool QWebSocketServer::isOriginAllowed(const QString &origin) const