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
24 \brief Implements a TCP socket that talks the websocket protocol.
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.
30 This class was modeled after QAbstractSocket.
32 \sa QAbstractSocket, QTcpSocket
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.
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.
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.
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.
54 \snippet echoclient.cpp onTextMessageReceived
55 Whenever a message is received, we write it out.
59 \fn void QWebSocket::connected()
60 \brief Emitted when a connection is successfully established.
61 \sa open(), disconnected()
64 \fn void QWebSocket::disconnected()
65 \brief Emitted when the socket is disconnected.
66 \sa close(), connected()
69 \fn void QWebSocket::aboutToClose()
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).
78 \fn void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
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.
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.
89 \sa QAuthenticator, QNetworkProxy
92 \fn void QWebSocket::stateChanged(QAbstractSocket::SocketState state);
94 This signal is emitted whenever QWebSocket's state changes.
95 The \a state parameter is the new state.
97 QAbstractSocket::SocketState is not a registered metatype, so for queued
98 connections, you will have to register it with Q_REGISTER_METATYPE() and
104 \fn void QWebSocket::readChannelFinished()
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.
112 \fn void QWebSocket::textFrameReceived(QString frame, bool isLastFrame);
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.
117 This signal can be used to process large messages frame by frame, instead of waiting for the complete
120 \sa binaryFrameReceived()
123 \fn void QWebSocket::binaryFrameReceived(QByteArray frame, bool isLastFrame);
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.
128 This signal can be used to process large messages frame by frame, instead of waiting for the complete
131 \sa textFrameReceived()
134 \fn void QWebSocket::textMessageReceived(QString message);
136 This signal is emitted whenever a text message is received. The \a message contains the received text.
138 \sa binaryMessageReceived()
141 \fn void QWebSocket::binaryMessageReceived(QByteArray message);
143 This signal is emitted whenever a binary message is received. The \a message contains the received bytes.
145 \sa textMessageReceived()
148 \fn void QWebSocket::error(QAbstractSocket::SocketError error);
150 This signal is emitted after an error occurred. The \a error
151 parameter describes the type of error that occurred.
153 QAbstractSocket::SocketError is not a registered metatype, so for queued
154 connections, you will have to register it with Q_DECLARE_METATYPE() and
157 \sa error(), errorString()
160 \fn void QWebSocket::pong(quint64 elapsedTime)
162 Emitted when a pong message is received in reply to a previous ping.
163 \a elapsedTime contains the roundtrip time in milliseconds
167 #include "qwebsocket.h"
168 #include "qwebsocket_p.h"
170 #include <QTcpSocket>
171 #include <QByteArray>
172 #include <QHostAddress>
180 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2; //maximum size of a frame when sending a message
183 * \brief Creates a new QWebSocket with the given \a origin, the \a version of the protocol to use and \a parent.
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
189 QWebSocket::QWebSocket(QString origin, QWebSocketProtocol::Version version, QObject *parent) :
191 d_ptr(new QWebSocketPrivate(origin, version, this, this))
196 * \brief Destroys the QWebSocket. Closes the socket if it is still open, and releases any used resources.
198 QWebSocket::~QWebSocket()
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.
207 void QWebSocket::abort()
213 * Returns the type of error that last occurred
216 QAbstractSocket::SocketError QWebSocket::error() const
218 return d_ptr->error();
221 //only called by QWebSocketPrivate::upgradeFrom
225 QWebSocket::QWebSocket(QTcpSocket *pTcpSocket, QWebSocketProtocol::Version version, QObject *parent) :
227 d_ptr(new QWebSocketPrivate(pTcpSocket, version, this, this))
232 * Returns a human-readable description of the last error that occurred
236 QString QWebSocket::errorString() const
238 return d_ptr->errorString();
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.
249 bool QWebSocket::flush()
251 return d_ptr->flush();
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.
258 qint64 QWebSocket::write(const char *message)
260 return d_ptr->write(message);
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.
266 qint64 QWebSocket::write(const char *message, qint64 maxSize)
268 return d_ptr->write(message, maxSize);
272 \brief Sends the given \a message over the socket as a text message and returns the number of bytes actually sent.
274 qint64 QWebSocket::write(const QString &message)
276 return d_ptr->write(message);
280 \brief Sends the given \a data over the socket as a binary message and returns the number of bytes actually sent.
282 qint64 QWebSocket::write(const QByteArray &data)
284 return d_ptr->write(data);
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
292 void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
294 d_ptr->close(closeCode, reason);
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
302 void QWebSocket::open(const QUrl &url, bool mask)
304 d_ptr->open(url, mask);
308 \brief Pings the server to indicate that the connection is still alive.
312 void QWebSocket::ping()
318 \brief Returns the version the socket is currently using
320 QWebSocketProtocol::Version QWebSocket::version()
322 return d_ptr->version();
326 \brief Returns the name of the resource currently accessed.
328 QString QWebSocket::resourceName()
330 return d_ptr->resourceName();
334 \brief Returns the url the socket is connected to or will connect to.
336 QUrl QWebSocket::requestUrl()
338 return d_ptr->requestUrl();
342 \brief Returns the current origin
344 QString QWebSocket::origin()
346 return d_ptr->origin();
350 \brief Returns the currently used protocol.
352 QString QWebSocket::protocol()
354 return d_ptr->protocol();
358 \brief Returns the currently used extension.
360 QString QWebSocket::extension()
362 return d_ptr->extension();
366 \brief Returns the current state of the socket
368 QAbstractSocket::SocketState QWebSocket::state() const
370 return d_ptr->state();
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:
378 socket->open("ws://localhost:1234", false);
379 if (socket->waitForConnected(1000))
381 qDebug("Connected!");
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.
389 \sa connected(), open(), state()
391 bool QWebSocket::waitForConnected(int msecs)
393 return d_ptr->waitForConnected(msecs);
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.
404 bool QWebSocket::waitForDisconnected(int msecs)
406 return d_ptr->waitForDisconnected(msecs);
410 Returns the local address
412 QHostAddress QWebSocket::localAddress() const
414 return d_ptr->localAddress();
418 Returns the local port
420 quint16 QWebSocket::localPort() const
422 return d_ptr->localPort();
426 Returns the pause mode of this socket
428 QAbstractSocket::PauseModes QWebSocket::pauseMode() const
430 return d_ptr->pauseMode();
434 Returns the peer address
436 QHostAddress QWebSocket::peerAddress() const
438 return d_ptr->peerAddress();
444 QString QWebSocket::peerName() const
446 return d_ptr->peerName();
452 quint16 QWebSocket::peerPort() const
454 return d_ptr->peerPort();
457 #ifndef QT_NO_NETWORKPROXY
459 Returns the currently configured proxy
461 QNetworkProxy QWebSocket::proxy() const
463 return d_ptr->proxy();
467 Sets the proxy to \a networkProxy
469 void QWebSocket::setProxy(const QNetworkProxy &networkProxy)
471 d_ptr->setProxy(networkProxy);
476 Returns the size in bytes of the readbuffer that is used by the socket.
478 qint64 QWebSocket::readBufferSize() const
480 return d_ptr->readBufferSize();
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.
489 \sa pauseMode(), setPauseMode()
491 void QWebSocket::resume()
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.
505 \sa pauseMode(), resume()
507 void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
509 d_ptr->setPauseMode(pauseMode);
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.
519 void QWebSocket::setReadBufferSize(qint64 size)
521 d_ptr->setReadBufferSize(size);
525 Sets the given \a option to the value described by \a value.
528 void QWebSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
530 d_ptr->setSocketOption(option, value);
534 Returns the value of the option \a option.
535 \sa setSocketOption()
537 QVariant QWebSocket::socketOption(QAbstractSocket::SocketOption option)
539 return d_ptr->socketOption(option);
543 Returns true if the QWebSocket is valid.
545 bool QWebSocket::isValid()
547 return d_ptr->isValid();