Added check on QT_NO_NETWORKPROXY to include proxy functionality only when required
[contrib/qtwebsockets.git] / src / qwebsocketserver.cpp
1 /*!
2         \class WebSocketServer
3
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
10
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.
18
19         \ref echoserver
20
21         \author Kurt Pattyn (pattyn.kurt@gmail.com)
22
23         \sa WebSocket
24 */
25
26 /*!
27   \page echoserver WebSocket server example
28   \brief A sample websocket server echoing back messages sent to it.
29
30   \section Description
31   The echoserver example implements a web socket server that echoes back everything that is sent to it.
32   \section Code
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.
37
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).
42
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.
48
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.
52 */
53
54 /*!
55         \fn void WebSocketServer::newConnection()
56         This signal is emitted every time a new connection is available.
57
58         \sa hasPendingConnections() and nextPendingConnection().
59 */
60
61 #include <QTcpServer>
62 #include <QTcpSocket>
63 #include <QNetworkProxy>
64 #include "qwebsocketprotocol.h"
65 #include "qwebsocket.h"
66 #include "qwebsocketserver.h"
67 #include "qwebsocketserver_p.h"
68
69 QT_BEGIN_NAMESPACE
70
71 /*!
72         Constructs a new WebSocketServer.
73
74         \a parent is passed to the QObject constructor.
75  */
76 QWebSocketServer::QWebSocketServer(const QString &serverName, QObject *parent) :
77         QObject(parent),
78         d_ptr(new QWebSocketServerPrivate(serverName, this, this))
79 {
80 }
81
82 /*!
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.
85
86         \sa close()
87  */
88 QWebSocketServer::~QWebSocketServer()
89 {
90         delete d_ptr;
91 }
92
93 /*!
94   Closes the server. The server will no longer listen for incoming connections.
95  */
96 void QWebSocketServer::close()
97 {
98         d_ptr->close();
99 }
100
101 /*!
102         Returns a human readable description of the last error that occurred.
103
104         \sa serverError().
105 */
106 QString QWebSocketServer::errorString() const
107 {
108         return d_ptr->errorString();
109 }
110
111 /*!
112         Returns true if the server has pending connections; otherwise returns false.
113
114         \sa nextPendingConnection() and setMaxPendingConnections().
115  */
116 bool QWebSocketServer::hasPendingConnections() const
117 {
118         return d_ptr->hasPendingConnections();
119 }
120
121 /*!
122         Returns true if the server is currently listening for incoming connections; otherwise returns false.
123
124         \sa listen().
125  */
126 bool QWebSocketServer::isListening() const
127 {
128         return d_ptr->isListening();
129 }
130
131 /*!
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.
135
136         Returns true on success; otherwise returns false.
137
138         \sa isListening().
139  */
140 bool QWebSocketServer::listen(const QHostAddress &address, quint16 port)
141 {
142         return d_ptr->listen(address, port);
143 }
144
145 /*!
146         Returns the maximum number of pending accepted connections. The default is 30.
147
148         \sa setMaxPendingConnections() and hasPendingConnections().
149  */
150 int QWebSocketServer::maxPendingConnections() const
151 {
152         return d_ptr->maxPendingConnections();
153 }
154
155 /*!
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.
159
160         Note: The returned WebSocket object cannot be used from another thread..
161
162         \sa hasPendingConnections().
163 */
164 QWebSocket *QWebSocketServer::nextPendingConnection()
165 {
166         return d_ptr->nextPendingConnection();
167 }
168
169 /*!
170 #ifndef QT_NO_NETWORKPROXY
171 /*!
172         Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used.
173
174         \sa setProxy().
175 */
176 QNetworkProxy QWebSocketServer::proxy() const
177 {
178         return d_ptr->proxy();
179 }
180
181 /*!
182         \brief Sets the explicit network proxy for this socket to \a networkProxy.
183
184         To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:
185
186         \code
187                 server->setProxy(QNetworkProxy::NoProxy);
188         \endcode
189
190         \sa proxy().
191 */
192 void QWebSocketServer::setProxy(const QNetworkProxy &networkProxy)
193 {
194         d_ptr->setProxy(networkProxy);
195 }
196 #endif
197         Returns the server's address if the server is listening for connections; otherwise returns QHostAddress::Null.
198
199         \sa serverPort() and listen().
200  */
201 QHostAddress QWebSocketServer::serverAddress() const
202 {
203         return d_ptr->serverAddress();
204 }
205
206 /*!
207         Returns an error code for the last error that occurred.
208         \sa errorString().
209  */
210 QAbstractSocket::SocketError QWebSocketServer::serverError() const
211 {
212         return d_ptr->serverError();
213 }
214
215 /*!
216         Returns the server's port if the server is listening for connections; otherwise returns 0.
217         \sa serverAddress() and listen().
218  */
219 quint16 QWebSocketServer::serverPort() const
220 {
221         return d_ptr->serverPort();
222 }
223
224 /*!
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.
228
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().
231  */
232 void QWebSocketServer::setMaxPendingConnections(int numConnections)
233 {
234         d_ptr->setMaxPendingConnections(numConnections);
235 }
236
237 /*!
238         Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor.
239
240         Returns true if the socket is set successfully; otherwise returns false.\n
241         The socket is assumed to be in listening state.
242
243         \sa socketDescriptor() and isListening().
244  */
245 bool QWebSocketServer::setSocketDescriptor(int socketDescriptor)
246 {
247         return d_ptr->setSocketDescriptor(socketDescriptor);
248 }
249
250 /*!
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.
253
254         \sa setSocketDescriptor() and isListening().
255  */
256 int QWebSocketServer::socketDescriptor() const
257 {
258         return d_ptr->socketDescriptor();
259 }
260
261 /*!
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.
265
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.
269
270         If \a msec is -1, this function will not time out.
271
272         \sa hasPendingConnections() and nextPendingConnection().
273 */
274 bool QWebSocketServer::waitForNewConnection(int msec, bool *timedOut)
275 {
276         return d_ptr->waitForNewConnection(msec, timedOut);
277 }
278
279 /*!
280   Returns a list of websocket versions that this server is supporting.
281  */
282 QList<QWebSocketProtocol::Version> QWebSocketServer::supportedVersions() const
283 {
284         return d_ptr->supportedVersions();
285 }
286
287 /*!
288   Returns a list of websocket subprotocols that this server supports.
289  */
290 QList<QString> QWebSocketServer::supportedProtocols() const
291 {
292         return d_ptr->supportedProtocols();
293 }
294
295 /*!
296   Returns a list of websocket extensions that this server supports.
297  */
298 QList<QString> QWebSocketServer::supportedExtensions() const
299 {
300         return d_ptr->supportedExtensions();
301 }
302
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
308 {
309         Q_UNUSED(origin)
310         return true;
311 }
312
313 QT_END_NAMESPACE