QWebSocket Class
Implements a TCP socket that talks the WebSocket protocol. More...
Header: | #include <QWebSocket> |
qmake: | QT += websockets |
Since: | Qt 5.3 |
Inherits: | QObject. |
Public Functions
QWebSocket(const QString & origin = QString(), QWebSocketProtocol::Version version = QWebSocketProtocol::VersionLatest, QObject * parent = 0) | |
virtual | ~QWebSocket() |
void | abort() |
QWebSocketProtocol::CloseCode | closeCode() const |
QString | closeReason() const |
QAbstractSocket::SocketError | error() const |
QString | errorString() const |
bool | flush() |
void | ignoreSslErrors(const QList<QSslError> & errors) |
bool | isValid() const |
QHostAddress | localAddress() const |
quint16 | localPort() const |
const QMaskGenerator * | maskGenerator() const |
QString | origin() const |
QAbstractSocket::PauseModes | pauseMode() const |
QHostAddress | peerAddress() const |
QString | peerName() const |
quint16 | peerPort() const |
QNetworkProxy | proxy() const |
qint64 | readBufferSize() const |
QUrl | requestUrl() const |
QString | resourceName() const |
void | resume() |
qint64 | sendBinaryMessage(const QByteArray & data) |
qint64 | sendTextMessage(const QString & message) |
void | setMaskGenerator(const QMaskGenerator * maskGenerator) |
void | setPauseMode(QAbstractSocket::PauseModes pauseMode) |
void | setProxy(const QNetworkProxy & networkProxy) |
void | setReadBufferSize(qint64 size) |
void | setSslConfiguration(const QSslConfiguration & sslConfiguration) |
QSslConfiguration | sslConfiguration() const |
QAbstractSocket::SocketState | state() const |
QWebSocketProtocol::Version | version() const |
- 31 public functions inherited from QObject
Public Slots
void | close(QWebSocketProtocol::CloseCode closeCode = QWebSocketProtocol::CloseCodeNormal, const QString & reason = QString()) |
void | ignoreSslErrors() |
void | open(const QUrl & url) |
void | ping(const QByteArray & payload = QByteArray()) |
- 1 public slot inherited from QObject
Signals
void | aboutToClose() |
void | binaryFrameReceived(const QByteArray & frame, bool isLastFrame) |
void | binaryMessageReceived(const QByteArray & message) |
void | bytesWritten(qint64 bytes) |
void | connected() |
void | disconnected() |
void | error(QAbstractSocket::SocketError error) |
void | pong(quint64 elapsedTime, const QByteArray & payload) |
void | proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator) |
void | readChannelFinished() |
void | sslErrors(const QList<QSslError> & errors) |
void | stateChanged(QAbstractSocket::SocketState state) |
void | textFrameReceived(const QString & frame, bool isLastFrame) |
void | textMessageReceived(const QString & message) |
- 2 signals inherited from QObject
Additional Inherited Members
- 1 property inherited from QObject
- 11 static public members inherited from QObject
- 9 protected functions inherited from QObject
Detailed Description
Implements a TCP socket that talks the WebSocket protocol.
WebSockets is a web technology providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011. QWebSocket can both be used in a client application and server application.
This class was modeled after QAbstractSocket.
QWebSocket currently does not support extensions and subprotocols.
QWebSocket only supports version 13 of the WebSocket protocol, as outlined in RFC 6455.
Note: Some proxies do not understand certain HTTP headers used during a WebSocket handshake. In that case, non-secure WebSocket connections fail. The best way to mitigate against this problem is to use WebSocket over a secure connection.
Warning: To generate masks, this implementation of WebSockets uses the cryptographically insecure qrand() function. For more information about the importance of good masking, see http://w2spconf.com/2011/papers/websocket.pdf. The best measure against attacks mentioned in the document above, is to use QWebSocket over a secure connection (wss://). In general, always be careful to not have 3rd party script access to a QWebSocket in your application.
See also QAbstractSocket, QTcpSocket, and QWebSocket client example.
Member Function Documentation
QWebSocket::QWebSocket(const QString & origin = QString(), QWebSocketProtocol::Version version = QWebSocketProtocol::VersionLatest, QObject * parent = 0)
Creates a new QWebSocket with the given origin, the version of the protocol to use and parent.
The origin of the client is as specified in RFC 6454. (The origin is not required for non-web browser clients (see RFC 6455)). The origin may not contain new line characters, otherwise the connection will be aborted immediately during the handshake phase.
Note: Currently only V13 (RFC 6455) is supported
[virtual]
QWebSocket::~QWebSocket()
Destroys the QWebSocket. Closes the socket if it is still open, and releases any used resources.
void QWebSocket::abort()
Aborts the current socket and resets the socket. Unlike close(), this function immediately closes the socket, discarding any pending data in the write buffer.
[signal]
void QWebSocket::aboutToClose()
This signal is emitted when the socket is about to close. Connect this signal if you have operations that need to be performed before the socket closes (e.g., if you have data in a separate buffer that needs to be written to the device).
See also close().
[signal]
void QWebSocket::binaryFrameReceived(const QByteArray & frame, bool isLastFrame)
This signal is emitted whenever a binary frame is received. The frame contains the data and isLastFrame indicates whether this is the last frame of the complete message.
This signal can be used to process large messages frame by frame, instead of waiting for the complete message to arrive.
See also textFrameReceived().
[signal]
void QWebSocket::binaryMessageReceived(const QByteArray & message)
This signal is emitted whenever a binary message is received. The message contains the received bytes.
See also textMessageReceived().
[signal]
void QWebSocket::bytesWritten(qint64 bytes)
This signal is emitted every time a payload of data has been written to the socket. The bytes argument is set to the number of bytes that were written in this payload.
Note: This signal has the same meaning both for secure and non-secure WebSockets. As opposed to QSslSocket, bytesWritten() is only emitted when encrypted data is effectively written (see QSslSocket::encryptedBytesWritten()).
See also close().
[slot]
void QWebSocket::close(QWebSocketProtocol::CloseCode closeCode = QWebSocketProtocol::CloseCodeNormal, const QString & reason = QString())
Gracefully closes the socket with the given closeCode and reason.
Any data in the write buffer is flushed before the socket is closed. The closeCode is a QWebSocketProtocol::CloseCode indicating the reason to close, and reason describes the reason of the closure more in detail
QWebSocketProtocol::CloseCode QWebSocket::closeCode() const
Returns the code indicating why the socket was closed.
See also QWebSocketProtocol::CloseCode and closeReason().
QString QWebSocket::closeReason() const
Returns the reason why the socket was closed.
See also closeCode().
[signal]
void QWebSocket::connected()
Emitted when a connection is successfully established. A connection is successfully established when the socket is connected and the handshake was successful.
See also open() and disconnected().
[signal]
void QWebSocket::disconnected()
Emitted when the socket is disconnected.
See also close() and connected().
QAbstractSocket::SocketError QWebSocket::error() const
Returns the type of error that last occurred
See also errorString().
[signal]
void QWebSocket::error(QAbstractSocket::SocketError error)
This signal is emitted after an error occurred. The error parameter describes the type of error that occurred.
QAbstractSocket::SocketError is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().
See also error() and errorString().
QString QWebSocket::errorString() const
Returns a human-readable description of the last error that occurred
See also error().
bool QWebSocket::flush()
This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true; otherwise false is returned. Call this function if you need QWebSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. 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.
[slot]
void QWebSocket::ignoreSslErrors()
This slot tells QWebSocket to ignore errors during QWebSocket's handshake phase and continue connecting. If you want to continue with the connection even if errors occur during the handshake phase, then you must call this slot, either from a slot connected to sslErrors(), or before the handshake phase. If you don't call this slot, either in response to errors or before the handshake, the connection will be dropped after the sslErrors() signal has been emitted.
Warning: Be sure to always let the user inspect the errors reported by the sslErrors() signal, and only call this method upon confirmation from the user that proceeding is ok. If there are unexpected errors, the connection should be aborted. Calling this method without inspecting the actual errors will most likely pose a security risk for your application. Use it with great care!
See also sslErrors(), QSslSocket::ignoreSslErrors(), and QNetworkReply::ignoreSslErrors().
void QWebSocket::ignoreSslErrors(const QList<QSslError> & errors)
This is an overloaded function.
This method tells QWebSocket to ignore the errors given in errors.
Note that you can set the expected certificate in the SSL error: If, for instance, you want to connect to a server that uses a self-signed certificate, consider the following snippet:
QList<QSslCertificate> cert = QSslCertificate::fromPath(QLatin1String("server-certificate.pem")); QSslError error(QSslError::SelfSignedCertificate, cert.at(0)); QList<QSslError> expectedSslErrors; expectedSslErrors.append(error); QWebSocket socket; socket.ignoreSslErrors(expectedSslErrors); socket.open(QUrl(QStringLiteral("wss://myserver.at.home")));
Multiple calls to this function will replace the list of errors that were passed in previous calls. You can clear the list of errors you want to ignore by calling this function with an empty list.
See also sslErrors().
bool QWebSocket::isValid() const
Returns true
if the socket is ready for reading and writing; otherwise returns false
.
QHostAddress QWebSocket::localAddress() const
Returns the local address
quint16 QWebSocket::localPort() const
Returns the local port
const QMaskGenerator * QWebSocket::maskGenerator() const
Returns the mask generator that is currently used by this QWebSocket.
See also setMaskGenerator().
[slot]
void QWebSocket::open(const QUrl & url)
Opens a WebSocket connection using the given url.
If the url contains newline characters (\r\n), then the error signal will be emitted with QAbstractSocket::ConnectionRefusedError as error type.
QString QWebSocket::origin() const
Returns the current origin.
QAbstractSocket::PauseModes QWebSocket::pauseMode() const
Returns the pause mode of this socket
See also setPauseMode().
QHostAddress QWebSocket::peerAddress() const
Returns the peer address
QString QWebSocket::peerName() const
Returns the peerName
quint16 QWebSocket::peerPort() const
Returns the peerport
[slot]
void QWebSocket::ping(const QByteArray & payload = QByteArray())
Pings the server to indicate that the connection is still alive. Additional payload can be sent along the ping message.
The size of the payload cannot be bigger than 125. If it is larger, the payload is clipped to 125 bytes.
See also pong().
[signal]
void QWebSocket::pong(quint64 elapsedTime, const QByteArray & payload)
Emitted when a pong message is received in reply to a previous ping. elapsedTime contains the roundtrip time in milliseconds and payload contains an optional payload that was sent with the ping.
See also ping().
QNetworkProxy QWebSocket::proxy() const
Returns the currently configured proxy
See also setProxy().
[signal]
void QWebSocket::proxyAuthenticationRequired(const QNetworkProxy & proxy, QAuthenticator * authenticator)
This signal can be emitted when a proxy that requires authentication is used. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.
Note: It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.
See also QAuthenticator and QNetworkProxy.
qint64 QWebSocket::readBufferSize() const
Returns the size in bytes of the readbuffer that is used by the socket.
See also setReadBufferSize().
[signal]
void QWebSocket::readChannelFinished()
This signal is emitted when the input (reading) stream is closed in this device. It is emitted as soon as the closing is detected.
See also close().
QUrl QWebSocket::requestUrl() const
Returns the url the socket is connected to or will connect to.
QString QWebSocket::resourceName() const
Returns the name of the resource currently accessed.
void QWebSocket::resume()
Continues data transfer on the socket. This method should only be used after the socket has been set to pause upon notifications and a notification has been received. The only notification currently supported is sslErrors(). Calling this method if the socket is not paused results in undefined behavior.
See also pauseMode() and setPauseMode().
qint64 QWebSocket::sendBinaryMessage(const QByteArray & data)
Sends the given data over the socket as a binary message and returns the number of bytes actually sent.
See also sendTextMessage().
qint64 QWebSocket::sendTextMessage(const QString & message)
Sends the given message over the socket as a text message and returns the number of bytes actually sent.
See also sendBinaryMessage().
void QWebSocket::setMaskGenerator(const QMaskGenerator * maskGenerator)
Sets the generator to use for creating masks to maskGenerator. The default QWebSocket generator can be reset by supplying a Q_NULLPTR. The mask generator can be changed at any time, even while the connection is open.
See also maskGenerator().
void QWebSocket::setPauseMode(QAbstractSocket::PauseModes pauseMode)
Controls whether to pause upon receiving a notification. The pauseMode parameter specifies the conditions in which the socket should be paused.
The only notification currently supported is sslErrors(). If set to PauseOnSslErrors, data transfer on the socket will be paused and needs to be enabled explicitly again by calling resume(). By default, this option is set to PauseNever. This option must be called before connecting to the server, otherwise it will result in undefined behavior.
See also pauseMode() and resume().
void QWebSocket::setProxy(const QNetworkProxy & networkProxy)
Sets the proxy to networkProxy
See also proxy().
void QWebSocket::setReadBufferSize(qint64 size)
Sets the size of QWebSocket's internal read buffer to be size bytes.
If the buffer size is limited to a certain size, QWebSocket won't buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default. This option is useful if you only read the data at certain points in time (for example, 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.
See also readBufferSize().
void QWebSocket::setSslConfiguration(const QSslConfiguration & sslConfiguration)
Sets the socket's SSL configuration to be the contents of sslConfiguration.
This function sets the local certificate, the ciphers, the private key and the CA certificates to those stored in sslConfiguration. It is not possible to set the SSL-state related fields.
See also sslConfiguration().
QSslConfiguration QWebSocket::sslConfiguration() const
Returns the socket's SSL configuration state. The default SSL configuration of a socket is to use the default ciphers, default CA certificates, no local private key or certificate. The SSL configuration also contains fields that can change with time without notice.
See also setSslConfiguration().
[signal]
void QWebSocket::sslErrors(const QList<QSslError> & errors)
QWebSocket emits this signal after the SSL handshake to indicate that one or more errors have occurred while establishing the identity of the peer. The errors are usually an indication that QWebSocket is unable to securely identify the peer. Unless any action is taken, the connection will be dropped after this signal has been emitted. 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. If you need to access the error list at a later point, you can call sslErrors() (without arguments).
errors contains one or more errors that prevent QWebSocket from verifying the identity of the peer.
Note: You cannot use Qt::QueuedConnection when connecting to this signal, or calling QWebSocket::ignoreSslErrors() will have no effect.
QAbstractSocket::SocketState QWebSocket::state() const
Returns the current state of the socket.
[signal]
void QWebSocket::stateChanged(QAbstractSocket::SocketState state)
This signal is emitted whenever QWebSocket's state changes. The state parameter is the new state.
Note: QAbstractSocket::ConnectedState is emitted after the handshake with the server has succeeded.
QAbstractSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_REGISTER_METATYPE() and qRegisterMetaType().
See also state().
[signal]
void QWebSocket::textFrameReceived(const QString & frame, bool isLastFrame)
This signal is emitted whenever a text frame is received. The frame contains the data and isLastFrame indicates whether this is the last frame of the complete message.
This signal can be used to process large messages frame by frame, instead of waiting for the complete message to arrive.
See also binaryFrameReceived().
[signal]
void QWebSocket::textMessageReceived(const QString & message)
This signal is emitted whenever a text message is received. The message contains the received text.
See also binaryMessageReceived().
QWebSocketProtocol::Version QWebSocket::version() const
Returns the version the socket is currently using.
© 2015 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.