1 /****************************************************************************
3 ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtWebSockets module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
45 \inmodule QtWebSockets
46 \brief Implements a TCP socket that talks the websocket protocol.
48 WebSockets is a web technology providing full-duplex communications channels over a single TCP connection.
49 The WebSocket protocol was standardized by the IETF as \l {http://tools.ietf.org/html/rfc6455} {RFC 6455} in 2011.
50 It can both be used in a client application and server application.
52 This class was modeled after QAbstractSocket.
54 \sa QAbstractSocket, QTcpSocket
56 \sa {QWebSocket client example}
60 \page echoclient.html example
61 \title QWebSocket client example
62 \brief A sample websocket client that sends a message and displays the message that it receives back.
65 The EchoClient example implements a web socket client that sends a message to a websocket server and dumps the answer that it gets back.
66 This example should ideally be used with the EchoServer example.
68 We start by connecting to the `connected()` signal.
69 \snippet echoclient/echoclient.cpp constructor
70 After the connection, we open the socket to the given \a url.
72 \snippet echoclient/echoclient.cpp onConnected
73 When the client is connected successfully, we connect to the `onTextMessageReceived()` signal, and send out "Hello, world!".
74 If connected with the EchoServer, we will receive the same message back.
76 \snippet echoclient/echoclient.cpp onTextMessageReceived
77 Whenever a message is received, we write it out.
81 \fn void QWebSocket::connected()
82 \brief Emitted when a connection is successfully established.
83 \sa open(), disconnected()
86 \fn void QWebSocket::disconnected()
87 \brief Emitted when the socket is disconnected.
88 \sa close(), connected()
91 \fn void QWebSocket::aboutToClose()
93 This signal is emitted when the socket is about to close.
94 Connect this signal if you have operations that need to be performed before the socket closes
95 (e.g., if you have data in a separate buffer that needs to be written to the device).
100 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
102 This signal can be emitted when a \a proxy that requires
103 authentication is used. The \a authenticator object can then be
104 filled in with the required details to allow authentication and
105 continue the connection.
107 \note It is not possible to use a QueuedConnection to connect to
108 this signal, as the connection will fail if the authenticator has
109 not been filled in with new information when the signal returns.
111 \sa QAuthenticator, QNetworkProxy
114 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
116 This signal is emitted whenever QWebSocket's state changes.
117 The \a state parameter is the new state.
119 QAbstractSocket::SocketState is not a registered metatype, so for queued
120 connections, you will have to register it with Q_REGISTER_METATYPE() and
126 \fn void QWebSocket::readChannelFinished()
128 This signal is emitted when the input (reading) stream is closed in this device. It is emitted as soon as the closing is detected.
133 \fn void QWebSocket::bytesWritten(qint64 bytes)
135 This signal is emitted every time a payload of data has been written to the socket.
136 The \a bytes argument is set to the number of bytes that were written in this payload.
138 \note This signal has the same meaning both for secure and non-secure websockets.
139 As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively written (see QSslSocket:encryptedBytesWritten()).
144 \fn void QWebSocket::textFrameReceived(QString frame, bool isLastFrame);
146 This signal is emitted whenever a text frame is received. The \a frame contains the data and
147 \a isLastFrame indicates whether this is the last frame of the complete message.
149 This signal can be used to process large messages frame by frame, instead of waiting for the complete
152 \sa binaryFrameReceived()
155 \fn void QWebSocket::binaryFrameReceived(QByteArray frame, bool isLastFrame);
157 This signal is emitted whenever a binary frame is received. The \a frame contains the data and
158 \a isLastFrame indicates whether this is the last frame of the complete message.
160 This signal can be used to process large messages frame by frame, instead of waiting for the complete
163 \sa textFrameReceived()
166 \fn void QWebSocket::textMessageReceived(QString message);
168 This signal is emitted whenever a text message is received. The \a message contains the received text.
170 \sa binaryMessageReceived()
173 \fn void QWebSocket::binaryMessageReceived(QByteArray message);
175 This signal is emitted whenever a binary message is received. The \a message contains the received bytes.
177 \sa textMessageReceived()
180 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
182 This signal is emitted after an error occurred. The \a error
183 parameter describes the type of error that occurred.
185 QAbstractSocket::SocketError is not a registered metatype, so for queued
186 connections, you will have to register it with Q_DECLARE_METATYPE() and
189 \sa error(), errorString()
192 \fn void QWebSocket::sslErrors(const QList<QSslError> &errors)
193 QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have occurred
194 while establishing the identity of the peer.
195 The errors are usually an indication that QWebSocket is unable to securely identify the peer.
196 Unless any action is taken, the connection will be dropped after this signal has been emitted.
197 If you want to continue connecting despite the errors that have occurred, you must call QWebSocket::ignoreSslErrors() from inside a slot connected to this signal.
198 If you need to access the error list at a later point, you can call sslErrors() (without arguments).
200 \a errors contains one or more errors that prevent QWebSocket from verifying the identity of the peer.
202 \note You cannot use Qt::QueuedConnection when connecting to this signal, or calling QWebSocket::ignoreSslErrors() will have no effect.
205 \fn void QWebSocket::pong(quint64 elapsedTime, QByteArray payload)
207 Emitted when a pong message is received in reply to a previous ping.
208 \a elapsedTime contains the roundtrip time in milliseconds and \a payload contains an optional payload that was sent with the ping.
212 #include "qwebsocket.h"
213 #include "qwebsocket_p.h"
215 #include <QtCore/QUrl>
216 #include <QtNetwork/QTcpSocket>
217 #include <QtCore/QByteArray>
218 #include <QtNetwork/QHostAddress>
220 #include <QtCore/QDebug>
227 * \brief Creates a new QWebSocket with the given \a origin, the \a version of the protocol to use and \a parent.
229 * The \a origin of the client is as specified \l {http://tools.ietf.org/html/rfc6454} {RFC 6454}.
230 * (The \a origin is not required for non-web browser clients (see \l {http://tools.ietf.org/html/rfc6455} {RFC 6455})).
231 * \note Currently only V13 (\l {http://tools.ietf.org/html/rfc6455} {RFC 6455}) is supported
233 QWebSocket::QWebSocket(const QString &origin, QWebSocketProtocol::Version version, QObject *parent) :
235 d_ptr(new QWebSocketPrivate(origin, version, this, this))
240 * \brief Destroys the QWebSocket. Closes the socket if it is still open, and releases any used resources.
242 QWebSocket::~QWebSocket()
248 * \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.
250 void QWebSocket::abort()
257 * Returns the type of error that last occurred
260 QAbstractSocket::SocketError QWebSocket::error() const
262 Q_D(const QWebSocket);
266 //only called by QWebSocketPrivate::upgradeFrom
270 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version, QObject *parent) :
272 d_ptr(new QWebSocketPrivate(pTcpSocket, version, this, this))
277 * Returns a human-readable description of the last error that occurred
281 QString QWebSocket::errorString() const
283 Q_D(const QWebSocket);
284 return d->errorString();
288 This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking.
289 If any data was written, this function returns true; otherwise false is returned.
290 Call this function if you need QWebSocket to start sending buffered data immediately.
291 The number of bytes successfully written depends on the operating system.
292 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.
293 In the absence of an event loop, call waitForBytesWritten() instead.
295 bool QWebSocket::flush()
302 Sends the given \a message over the socket as a text message and returns the number of bytes actually sent.
303 \a message must be '\\0' terminated.
305 qint64 QWebSocket::write(const char *message)
308 return d->write(message);
312 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.
314 qint64 QWebSocket::write(const char *message, qint64 maxSize)
317 return d->write(message, maxSize);
321 \brief Sends the given \a message over the socket as a text message and returns the number of bytes actually sent.
323 qint64 QWebSocket::write(const QString &message)
326 return d->write(message);
330 \brief Sends the given \a data over the socket as a binary message and returns the number of bytes actually sent.
332 qint64 QWebSocket::write(const QByteArray &data)
335 return d->write(data);
339 \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.
340 The \a closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and
341 \a reason describes the reason of the closure more in detail
343 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, const QString &reason)
346 d->close(closeCode, reason);
350 \brief Opens a websocket connection using the given \a url.
351 If \a mask is true, all frames will be masked; this is only necessary for client side sockets; servers should never mask
352 \note A client socket must *always* mask its frames; servers may *never* mask its frames
354 void QWebSocket::open(const QUrl &url, bool mask)
361 \brief Pings the server to indicate that the connection is still alive.
362 Additional \a payload can be sent along the ping message.
364 The size of the \a payload cannot be bigger than 125. If it is larger, the \a payload is clipped to 125 bytes.
368 void QWebSocket::ping(const QByteArray &payload)
376 This slot tells QWebSocket to ignore errors during QWebSocket's
377 handshake phase and continue connecting. If you want to continue
378 with the connection even if errors occur during the handshake
379 phase, then you must call this slot, either from a slot connected
380 to sslErrors(), or before the handshake phase. If you don't call
381 this slot, either in response to errors or before the handshake,
382 the connection will be dropped after the sslErrors() signal has
385 \warning Be sure to always let the user inspect the errors
386 reported by the sslErrors() signal, and only call this method
387 upon confirmation from the user that proceeding is ok.
388 If there are unexpected errors, the connection should be aborted.
389 Calling this method without inspecting the actual errors will
390 most likely pose a security risk for your application. Use it
393 \sa sslErrors(), QSslSocket::ignoreSslErrors(), QNetworkReply::ignoreSslErrors()
395 void QWebSocket::ignoreSslErrors()
398 d->ignoreSslErrors();
404 This method tells QWebSocket to ignore the errors given in \a errors.
406 Note that you can set the expected certificate in the SSL error:
407 If, for instance, you want to connect to a server that uses
408 a self-signed certificate, consider the following snippet:
410 \snippet src_websockets_ssl_qwebsocket.cpp 6
412 Multiple calls to this function will replace the list of errors that
413 were passed in previous calls.
414 You can clear the list of errors you want to ignore by calling this
415 function with an empty list.
419 void QWebSocket::ignoreSslErrors(const QList<QSslError> &errors)
422 d->ignoreSslErrors(errors);
426 Sets the socket's SSL configuration to be the contents of \a sslConfiguration.
428 This function sets the local certificate, the ciphers, the private key and the CA certificates to those stored in \a sslConfiguration.
429 It is not possible to set the SSL-state related fields.
430 \sa sslConfiguration()
432 void QWebSocket::setSslConfiguration(const QSslConfiguration &sslConfiguration)
435 d->setSslConfiguration(sslConfiguration);
439 Returns the socket's SSL configuration state.
440 The default SSL configuration of a socket is to use the default ciphers, default CA certificates, no local private key or certificate.
441 The SSL configuration also contains fields that can change with time without notice.
443 \sa setSslConfiguration()
445 QSslConfiguration QWebSocket::sslConfiguration() const
447 Q_D(const QWebSocket);
448 return d->sslConfiguration();
451 #endif //not QT_NO_SSL
454 \brief Returns the version the socket is currently using
456 QWebSocketProtocol::Version QWebSocket::version() const
458 Q_D(const QWebSocket);
463 \brief Returns the name of the resource currently accessed.
465 QString QWebSocket::resourceName() const
467 Q_D(const QWebSocket);
468 return d->resourceName();
472 \brief Returns the url the socket is connected to or will connect to.
474 QUrl QWebSocket::requestUrl() const
476 Q_D(const QWebSocket);
477 return d->requestUrl();
481 \brief Returns the current origin
483 QString QWebSocket::origin() const
485 Q_D(const QWebSocket);
490 \brief Returns the currently used protocol.
492 QString QWebSocket::protocol() const
494 Q_D(const QWebSocket);
495 return d->protocol();
499 \brief Returns the currently used extension.
501 QString QWebSocket::extension() const
503 Q_D(const QWebSocket);
504 return d->extension();
508 \brief Returns the code indicating why the socket was closed.
509 \sa QWebSocketProtocol::CloseCode, closeReason()
511 QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
513 Q_D(const QWebSocket);
514 return d->closeCode();
518 \brief Returns the reason why the socket was closed.
521 QString QWebSocket::closeReason() const
523 Q_D(const QWebSocket);
524 return d->closeReason();
528 \brief Returns the current state of the socket
530 QAbstractSocket::SocketState QWebSocket::state() const
532 Q_D(const QWebSocket);
537 \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.
538 The following example waits up to one second for a connection to be established:
541 socket->open("ws://localhost:1234", false);
542 if (socket->waitForConnected(1000))
544 qDebug("Connected!");
548 If \a msecs is -1, this function will not time out.
549 @note This function may wait slightly longer than msecs, depending on the time it takes to complete the host lookup.
550 @note Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.
552 \sa connected(), open(), state()
554 bool QWebSocket::waitForConnected(int msecs)
557 return d->waitForConnected(msecs);
561 Waits \a msecs for the socket to be disconnected.
562 If the socket was successfully disconnected within time, this method returns true.
563 Otherwise false is returned.
564 When \a msecs is -1, this function will block until the socket is disconnected.
568 bool QWebSocket::waitForDisconnected(int msecs)
571 return d->waitForDisconnected(msecs);
575 Returns the local address
577 QHostAddress QWebSocket::localAddress() const
579 Q_D(const QWebSocket);
580 return d->localAddress();
584 Returns the local port
586 quint16 QWebSocket::localPort() const
588 Q_D(const QWebSocket);
589 return d->localPort();
593 Returns the pause mode of this socket
595 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
597 Q_D(const QWebSocket);
598 return d->pauseMode();
602 Returns the peer address
604 QHostAddress QWebSocket::peerAddress() const
606 Q_D(const QWebSocket);
607 return d->peerAddress();
613 QString QWebSocket::peerName() const
615 Q_D(const QWebSocket);
616 return d->peerName();
622 quint16 QWebSocket::peerPort() const
624 Q_D(const QWebSocket);
625 return d->peerPort();
628 #ifndef QT_NO_NETWORKPROXY
630 Returns the currently configured proxy
632 QNetworkProxy QWebSocket::proxy() const
634 Q_D(const QWebSocket);
639 Sets the proxy to \a networkProxy
641 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
644 d->setProxy(networkProxy);
649 Returns the size in bytes of the readbuffer that is used by the socket.
651 qint64 QWebSocket::readBufferSize() const
653 Q_D(const QWebSocket);
654 return d->readBufferSize();
658 Continues data transfer on the socket. This method should only be used after the socket
659 has been set to pause upon notifications and a notification has been received.
660 The only notification currently supported is sslErrors().
661 Calling this method if the socket is not paused results in undefined behavior.
663 \sa pauseMode(), setPauseMode()
665 void QWebSocket::resume()
672 Controls whether to pause upon receiving a notification. The \a pauseMode parameter specifies
673 the conditions in which the socket should be paused.
674 The only notification currently supported is sslErrors().
675 If set to PauseOnSslErrors, data transfer on the socket will be paused
676 and needs to be enabled explicitly again by calling resume().
677 By default, this option is set to PauseNever. This option must be called
678 before connecting to the server, otherwise it will result in undefined behavior.
680 \sa pauseMode(), resume()
682 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
685 d->setPauseMode(pauseMode);
689 Sets the size of QWebSocket's internal read buffer to be \a size bytes.
690 If the buffer size is limited to a certain size, QWebSocket won't buffer more than this size of data.
691 Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.
692 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.
695 void QWebSocket::setReadBufferSize(qint64 size)
698 d->setReadBufferSize(size);
702 Sets the given \a option to the value described by \a value.
705 void QWebSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
708 d->setSocketOption(option, value);
712 Returns the value of the option \a option.
713 \sa setSocketOption()
715 QVariant QWebSocket::socketOption(QAbstractSocket::SocketOption option)
718 return d->socketOption(option);
722 Returns true if the QWebSocket is valid.
724 bool QWebSocket::isValid() const
726 Q_D(const QWebSocket);