Made accessor methods const; made serverName parameter const in QWebSocket
[contrib/qtwebsockets.git] / src / qwebsocket.cpp
1 /*
2 QWebSockets implements the WebSocket protocol as defined in RFC 6455.
3 Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
4
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.
9
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.
14
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
18 */
19
20 /*!
21     \class QWebSocket
22
23     \inmodule QWebSockets
24     \brief Implements a TCP socket that talks the websocket protocol.
25
26     WebSockets is a web technology providing full-duplex communications channels over a single TCP connection.
27     The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011 (see http://tools.ietf.org/html/rfc6455).
28     It can both be used in a client application and server application.
29
30     This class was modeled after QAbstractSocket.
31
32     \sa QAbstractSocket, QTcpSocket
33
34     \sa echoclient.html
35 */
36
37 /*!
38     \page echoclient.html example
39     \title QWebSocket client example
40     \brief A sample websocket client that sends a message and displays the message that it receives back.
41
42     \section1 Description
43     The EchoClient example implements a web socket client that sends a message to a websocket server and dumps the answer that it gets back.
44     This example should ideally be used with the EchoServer example.
45     \section1 Code
46     We start by connecting to the `connected()` signal.
47     \snippet echoclient.cpp constructor
48     After the connection, we open the socket to the given \a url.
49
50     \snippet echoclient.cpp onConnected
51     When the client is connected successfully, we connect to the `onTextMessageReceived()` signal, and send out "Hello, world!".
52     If connected with the EchoServer, we will receive the same message back.
53
54     \snippet echoclient.cpp onTextMessageReceived
55     Whenever a message is received, we write it out.
56 */
57
58 /*!
59   \fn void QWebSocket::connected()
60   \brief Emitted when a connection is successfully established.
61   \sa open(), disconnected()
62 */
63 /*!
64   \fn void QWebSocket::disconnected()
65   \brief Emitted when the socket is disconnected.
66   \sa close(), connected()
67 */
68 /*!
69     \fn void QWebSocket::aboutToClose()
70
71     This signal is emitted when the socket is about to close.
72     Connect this signal if you have operations that need to be performed before the socket closes
73     (e.g., if you have data in a separate buffer that needs to be written to the device).
74
75     \sa close()
76  */
77 /*!
78 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
79
80 This signal can be emitted when a \a proxy that requires
81 authentication is used. The \a authenticator object can then be
82 filled in with the required details to allow authentication and
83 continue the connection.
84
85 \note It is not possible to use a QueuedConnection to connect to
86 this signal, as the connection will fail if the authenticator has
87 not been filled in with new information when the signal returns.
88
89 \sa QAuthenticator, QNetworkProxy
90 */
91 /*!
92     \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
93
94     This signal is emitted whenever QWebSocket's state changes.
95     The \a state parameter is the new state.
96
97     QAbstractSocket::SocketState is not a registered metatype, so for queued
98     connections, you will have to register it with Q_REGISTER_METATYPE() and
99     qRegisterMetaType().
100
101     \sa state()
102 */
103 /*!
104     \fn void QWebSocket::readChannelFinished()
105
106     This signal is emitted when the input (reading) stream is closed in this device. It is emitted as soon as the closing is detected.
107
108     \sa close()
109 */
110
111 /*!
112     \fn void QWebSocket::textFrameReceived(QString frame, bool isLastFrame);
113
114     This signal is emitted whenever a text frame is received. The \a frame contains the data and
115     \a isLastFrame indicates whether this is the last frame of the complete message.
116
117     This signal can be used to process large messages frame by frame, instead of waiting for the complete
118     message to arrive.
119
120     \sa binaryFrameReceived()
121 */
122 /*!
123     \fn void QWebSocket::binaryFrameReceived(QByteArray frame, bool isLastFrame);
124
125     This signal is emitted whenever a binary frame is received. The \a frame contains the data and
126     \a isLastFrame indicates whether this is the last frame of the complete message.
127
128     This signal can be used to process large messages frame by frame, instead of waiting for the complete
129     message to arrive.
130
131     \sa textFrameReceived()
132 */
133 /*!
134     \fn void QWebSocket::textMessageReceived(QString message);
135
136     This signal is emitted whenever a text message is received. The \a message contains the received text.
137
138     \sa binaryMessageReceived()
139 */
140 /*!
141     \fn void QWebSocket::binaryMessageReceived(QByteArray message);
142
143     This signal is emitted whenever a binary message is received. The \a message contains the received bytes.
144
145     \sa textMessageReceived()
146 */
147 /*!
148     \fn void QWebSocket::error(QAbstractSocket::SocketError error);
149
150     This signal is emitted after an error occurred. The \a error
151     parameter describes the type of error that occurred.
152
153     QAbstractSocket::SocketError is not a registered metatype, so for queued
154     connections, you will have to register it with Q_DECLARE_METATYPE() and
155     qRegisterMetaType().
156
157     \sa error(), errorString()
158 */
159 /*!
160     \fn void QWebSocket::pong(quint64 elapsedTime)
161
162     Emitted when a pong message is received in reply to a previous ping.
163     \a elapsedTime contains the roundtrip time in milliseconds
164
165     \sa ping()
166   */
167 #include "qwebsocket.h"
168 #include "qwebsocket_p.h"
169 #include <QUrl>
170 #include <QTcpSocket>
171 #include <QByteArray>
172 #include <QHostAddress>
173
174 #include <QDebug>
175
176 #include <limits>
177
178 QT_BEGIN_NAMESPACE
179
180 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2;      //maximum size of a frame when sending a message
181
182 /*!
183  * \brief Creates a new QWebSocket with the given \a origin, the \a version of the protocol to use and \a parent.
184  *
185  * The \a origin of the client is as specified in http://tools.ietf.org/html/rfc6454.
186  * (The \a origin is not required for non-web browser clients (see RFC 6455)).
187  * \note Currently only V13 (RFC 6455) is supported
188  */
189 QWebSocket::QWebSocket(const QString &origin, QWebSocketProtocol::Version version, QObject *parent) :
190     QObject(parent),
191     d_ptr(new QWebSocketPrivate(origin, version, this, this))
192 {
193 }
194
195 /*!
196  * \brief Destroys the QWebSocket. Closes the socket if it is still open, and releases any used resources.
197  */
198 QWebSocket::~QWebSocket()
199 {
200     delete d_ptr;
201     //d_ptr = 0;
202 }
203
204 /*!
205  * \brief Aborts the current socket and resets the socket. Unlike close(), this function immediately closes the socket, discarding any pending data in the write buffer.
206  */
207 void QWebSocket::abort()
208 {
209     d_ptr->abort();
210 }
211
212 /*!
213  * Returns the type of error that last occurred
214  * \sa errorString()
215  */
216 QAbstractSocket::SocketError QWebSocket::error() const
217 {
218     return d_ptr->error();
219 }
220
221 //only called by QWebSocketPrivate::upgradeFrom
222 /*!
223   \internal
224  */
225 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version, QObject *parent) :
226     QObject(parent),
227     d_ptr(new QWebSocketPrivate(pTcpSocket, version, this, this))
228 {
229 }
230
231 /*!
232  * Returns a human-readable description of the last error that occurred
233  *
234  * \sa error()
235  */
236 QString QWebSocket::errorString() const
237 {
238     return d_ptr->errorString();
239 }
240
241 /*!
242     This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking.
243     If any data was written, this function returns true; otherwise false is returned.
244     Call this function if you need QWebSocket to start sending buffered data immediately.
245     The number of bytes successfully written depends on the operating system.
246     In most cases, you do not need to call this function, because QWebSocket will start sending data automatically once control goes back to the event loop.
247     In the absence of an event loop, call waitForBytesWritten() instead.
248 */
249 bool QWebSocket::flush()
250 {
251     return d_ptr->flush();
252 }
253
254 /*!
255     Sends the given \a message over the socket as a text message and returns the number of bytes actually sent.
256     \a message must be '\\0' terminated.
257  */
258 qint64 QWebSocket::write(const char *message)
259 {
260     return d_ptr->write(message);
261 }
262
263 /*!
264     Sends the most \a maxSize bytes of the given \a message over the socket as a text message and returns the number of bytes actually sent.
265  */
266 qint64 QWebSocket::write(const char *message, qint64 maxSize)
267 {
268     return d_ptr->write(message, maxSize);
269 }
270
271 /*!
272     \brief Sends the given \a message over the socket as a text message and returns the number of bytes actually sent.
273  */
274 qint64 QWebSocket::write(const QString &message)
275 {
276     return d_ptr->write(message);
277 }
278
279 /*!
280     \brief Sends the given \a data over the socket as a binary message and returns the number of bytes actually sent.
281  */
282 qint64 QWebSocket::write(const QByteArray &data)
283 {
284     return d_ptr->write(data);
285 }
286
287 /*!
288     \brief Gracefully closes the socket with the given \a closeCode and \a reason. Any data in the write buffer is flushed before the socket is closed.
289     The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
290     \a reason describes the reason of the closure more in detail
291  */
292 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
293 {
294     d_ptr->close(closeCode, reason);
295 }
296
297 /*!
298     \brief Opens a websocket connection using the given \a url.
299     If \a mask is true, all frames will be masked; this is only necessary for client side sockets; servers should never mask
300     \note A client socket must *always* mask its frames; servers may *never* mask its frames
301  */
302 void QWebSocket::open(const QUrl &url, bool mask)
303 {
304     d_ptr->open(url, mask);
305 }
306
307 /*!
308     \brief Pings the server to indicate that the connection is still alive.
309
310     \sa pong()
311  */
312 void QWebSocket::ping()
313 {
314     d_ptr->ping();
315 }
316
317 /*!
318     \brief Returns the version the socket is currently using
319  */
320 QWebSocketProtocol::Version QWebSocket::version() const
321 {
322     return d_ptr->version();
323 }
324
325 /*!
326     \brief Returns the name of the resource currently accessed.
327  */
328 QString QWebSocket::resourceName() const
329 {
330     return d_ptr->resourceName();
331 }
332
333 /*!
334     \brief Returns the url the socket is connected to or will connect to.
335  */
336 QUrl QWebSocket::requestUrl() const
337 {
338     return d_ptr->requestUrl();
339 }
340
341 /*!
342     \brief Returns the current origin
343  */
344 QString QWebSocket::origin() const
345 {
346     return d_ptr->origin();
347 }
348
349 /*!
350     \brief Returns the currently used protocol.
351  */
352 QString QWebSocket::protocol() const
353 {
354     return d_ptr->protocol();
355 }
356
357 /*!
358     \brief Returns the currently used extension.
359  */
360 QString QWebSocket::extension() const
361 {
362     return d_ptr->extension();
363 }
364
365 /*!
366     \brief Returns the current state of the socket
367  */
368 QAbstractSocket::SocketState QWebSocket::state() const
369 {
370     return d_ptr->state();
371 }
372
373 /*!
374     \brief Waits until the socket is connected, up to \a msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call error() to determine the cause of the error.
375     The following example waits up to one second for a connection to be established:
376
377     ~~~{.cpp}
378     socket->open("ws://localhost:1234", false);
379     if (socket->waitForConnected(1000))
380     {
381         qDebug("Connected!");
382     }
383     ~~~
384
385     If \a msecs is -1, this function will not time out.
386     @note This function may wait slightly longer than msecs, depending on the time it takes to complete the host lookup.
387     @note Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.
388
389     \sa connected(), open(), state()
390  */
391 bool QWebSocket::waitForConnected(int msecs)
392 {
393     return d_ptr->waitForConnected(msecs);
394 }
395
396 /*!
397   Waits \a msecs for the socket to be disconnected.
398   If the socket was successfully disconnected within time, this method returns true.
399   Otherwise false is returned.
400   When \a msecs is -1, this function will block until the socket is disconnected.
401
402   \sa close(), state()
403 */
404 bool QWebSocket::waitForDisconnected(int msecs)
405 {
406     return d_ptr->waitForDisconnected(msecs);
407 }
408
409 /*!
410     Returns the local address
411  */
412 QHostAddress QWebSocket::localAddress() const
413 {
414     return d_ptr->localAddress();
415 }
416
417 /*!
418     Returns the local port
419  */
420 quint16 QWebSocket::localPort() const
421 {
422     return d_ptr->localPort();
423 }
424
425 /*!
426     Returns the pause mode of this socket
427  */
428 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
429 {
430     return d_ptr->pauseMode();
431 }
432
433 /*!
434     Returns the peer address
435  */
436 QHostAddress QWebSocket::peerAddress() const
437 {
438     return d_ptr->peerAddress();
439 }
440
441 /*!
442     Returns the peerName
443  */
444 QString QWebSocket::peerName() const
445 {
446     return d_ptr->peerName();
447 }
448
449 /*!
450     Returns the peerport
451  */
452 quint16 QWebSocket::peerPort() const
453 {
454     return d_ptr->peerPort();
455 }
456
457 #ifndef QT_NO_NETWORKPROXY
458 /*!
459     Returns the currently configured proxy
460  */
461 QNetworkProxy QWebSocket::proxy() const
462 {
463     return d_ptr->proxy();
464 }
465
466 /*!
467     Sets the proxy to \a networkProxy
468  */
469 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
470 {
471     d_ptr->setProxy(networkProxy);
472 }
473 #endif
474
475 /*!
476     Returns the size in bytes of the readbuffer that is used by the socket.
477  */
478 qint64 QWebSocket::readBufferSize() const
479 {
480     return d_ptr->readBufferSize();
481 }
482
483 /*!
484     Continues data transfer on the socket. This method should only be used after the socket
485     has been set to pause upon notifications and a notification has been received.
486     The only notification currently supported is sslErrors().
487     Calling this method if the socket is not paused results in undefined behavior.
488
489     \sa pauseMode(), setPauseMode()
490  */
491 void QWebSocket::resume()
492 {
493     d_ptr->resume();
494 }
495
496 /*!
497     Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
498     the conditions in which the socket should be paused.
499     The only notification currently supported is sslErrors().
500     If set to PauseOnSslErrors, data transfer on the socket will be paused
501     and needs to be enabled explicitly again by calling resume().
502     By default, this option is set to PauseNever. This option must be called
503     before connecting to the server, otherwise it will result in undefined behavior.
504
505     \sa pauseMode(), resume()
506  */
507 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
508 {
509     d_ptr->setPauseMode(pauseMode);
510 }
511
512 /*!
513     Sets the size of QWebSocket's internal read buffer to be \a size bytes.
514     If the buffer size is limited to a certain size, QWebSocket won't buffer more than this size of data.
515     Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.
516     This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.
517     \sa readBufferSize()
518 */
519 void QWebSocket::setReadBufferSize(qint64 size)
520 {
521     d_ptr->setReadBufferSize(size);
522 }
523
524 /*!
525     Sets the given \a option to the value described by \a value.
526     \sa socketOption()
527 */
528 void QWebSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
529 {
530     d_ptr->setSocketOption(option, value);
531 }
532
533 /*!
534     Returns the value of the option \a option.
535     \sa setSocketOption()
536 */
537 QVariant QWebSocket::socketOption(QAbstractSocket::SocketOption option)
538 {
539     return d_ptr->socketOption(option);
540 }
541
542 /*!
543     Returns true if the QWebSocket is valid.
544  */
545 bool QWebSocket::isValid() const
546 {
547     return d_ptr->isValid();
548 }
549
550 QT_END_NAMESPACE