Cleanup code to comply with Qt style
[contrib/qtwebsockets.git] / src / websockets / qwebsocket_p.cpp
index 43cca86..d605617 100644 (file)
@@ -1,40 +1,68 @@
-/*
-QWebSockets implements the WebSocket protocol as defined in RFC 6455.
-Copyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)
-
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Lesser General Public
-License as published by the Free Software Foundation; either
-version 2.1 of the License, or (at your option) any later version.
-
-This library is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public
-License along with this library; if not, write to the Free Software
-Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-*/
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtWebSockets module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia.  For licensing terms and
+** conditions see http://qt.digia.com/licensing.  For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights.  These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file.  Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
 
 #include "qwebsocket.h"
 #include "qwebsocket_p.h"
+#include "qwebsocketprotocol_p.h"
 #include "qwebsockethandshakerequest_p.h"
 #include "qwebsockethandshakeresponse_p.h"
-#include <QUrl>
-#include <QTcpSocket>
-#include <QByteArray>
-#include <QtEndian>
-#include <QCryptographicHash>
-#include <QRegularExpression>
-#include <QStringList>
-#include <QHostAddress>
-#include <QStringBuilder>   //for more efficient string concatenation
+
+#include <QtCore/QUrl>
+#include <QtNetwork/QTcpSocket>
+#include <QtCore/QByteArray>
+#include <QtCore/QtEndian>
+#include <QtCore/QCryptographicHash>
+#include <QtCore/QRegularExpression>
+#include <QtCore/QStringList>
+#include <QtNetwork/QHostAddress>
+#include <QtCore/QStringBuilder>   //for more efficient string concatenation
 #ifndef QT_NONETWORKPROXY
-#include <QNetworkProxy>
+#include <QtNetwork/QNetworkProxy>
+#endif
+#ifndef QT_NO_SSL
+#include <QtNetwork/QSslConfiguration>
+#include <QtNetwork/QSslError>
 #endif
 
-#include <QDebug>
+#include <QtCore/QDebug>
 
 #include <limits>
 
@@ -42,13 +70,25 @@ QT_BEGIN_NAMESPACE
 
 const quint64 FRAME_SIZE_IN_BYTES = 512 * 512 * 2;     //maximum size of a frame when sending a message
 
+QWebSocketConfiguration::QWebSocketConfiguration() :
+#ifndef QT_NO_SSL
+    m_sslConfiguration(QSslConfiguration::defaultConfiguration()),
+    m_ignoredSslErrors(),
+    m_ignoreSslErrors(false),
+#endif
+#ifndef QT_NONETWORKPROXY
+    m_proxy(QNetworkProxy::DefaultProxy)
+#endif
+{
+}
+
 /*!
     \internal
 */
 QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::Version version, QWebSocket *pWebSocket, QObject *parent) :
     QObject(parent),
     q_ptr(pWebSocket),
-    m_pSocket(new QTcpSocket(this)),
+    m_pSocket(),
     m_errorString(),
     m_version(version),
     m_resourceName(),
@@ -61,11 +101,13 @@ QWebSocketPrivate::QWebSocketPrivate(const QString &origin, QWebSocketProtocol::
     m_mustMask(true),
     m_isClosingHandshakeSent(false),
     m_isClosingHandshakeReceived(false),
+    m_closeCode(QWebSocketProtocol::CC_NORMAL),
+    m_closeReason(),
     m_pingTimer(),
-    m_dataProcessor()
+    m_dataProcessor(),
+    m_configuration()
 {
     Q_ASSERT(pWebSocket);
-    makeConnections(m_pSocket);
     qsrand(static_cast<uint>(QDateTime::currentMSecsSinceEpoch()));
 }
 
@@ -88,11 +130,14 @@ QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol:
     m_mustMask(true),
     m_isClosingHandshakeSent(false),
     m_isClosingHandshakeReceived(false),
+    m_closeCode(QWebSocketProtocol::CC_NORMAL),
+    m_closeReason(),
     m_pingTimer(),
-    m_dataProcessor()
+    m_dataProcessor(),
+    m_configuration()
 {
     Q_ASSERT(pWebSocket);
-    makeConnections(m_pSocket);
+    makeConnections(m_pSocket.data());
 }
 
 /*!
@@ -100,13 +145,13 @@ QWebSocketPrivate::QWebSocketPrivate(QTcpSocket *pTcpSocket, QWebSocketProtocol:
 */
 QWebSocketPrivate::~QWebSocketPrivate()
 {
-    if (state() == QAbstractSocket::ConnectedState)
-    {
+    if (!m_pSocket) {
+        return;
+    }
+    if (state() == QAbstractSocket::ConnectedState) {
         close(QWebSocketProtocol::CC_GOING_AWAY, tr("Connection closed"));
     }
-    releaseConnections(m_pSocket);
-    m_pSocket->deleteLater();
-    m_pSocket = Q_NULLPTR;
+    releaseConnections(m_pSocket.data());
 }
 
 /*!
@@ -114,7 +159,9 @@ QWebSocketPrivate::~QWebSocketPrivate()
  */
 void QWebSocketPrivate::abort()
 {
-    m_pSocket->abort();
+    if (m_pSocket) {
+        m_pSocket->abort();
+    }
 }
 
 /*!
@@ -122,7 +169,11 @@ void QWebSocketPrivate::abort()
  */
 QAbstractSocket::SocketError QWebSocketPrivate::error() const
 {
-    return m_pSocket->error();
+    QAbstractSocket::SocketError err = QAbstractSocket::OperationError;
+    if (m_pSocket) {
+        err = m_pSocket->error();
+    }
+    return err;
 }
 
 /*!
@@ -130,14 +181,13 @@ QAbstractSocket::SocketError QWebSocketPrivate::error() const
  */
 QString QWebSocketPrivate::errorString() const
 {
-    if (!m_errorString.isEmpty())
-    {
-        return m_errorString;
-    }
-    else
-    {
-        return m_pSocket->errorString();
+    QString errMsg;
+    if (!m_errorString.isEmpty()) {
+        errMsg = m_errorString;
+    } else if (m_pSocket) {
+        errMsg = m_pSocket->errorString();
     }
+    return errMsg;
 }
 
 /*!
@@ -145,7 +195,11 @@ QString QWebSocketPrivate::errorString() const
  */
 bool QWebSocketPrivate::flush()
 {
-    return m_pSocket->flush();
+    bool result = true;
+    if (m_pSocket) {
+        result = m_pSocket->flush();
+    }
+    return result;
 }
 
 /*!
@@ -153,6 +207,8 @@ bool QWebSocketPrivate::flush()
  */
 qint64 QWebSocketPrivate::write(const char *message)
 {
+    //TODO: create a QByteArray from message, and directly call doWriteFrames
+    //now the data is converted to a string, and then converted back to a bytearray
     return write(QString::fromUtf8(message));
 }
 
@@ -161,6 +217,8 @@ qint64 QWebSocketPrivate::write(const char *message)
  */
 qint64 QWebSocketPrivate::write(const char *message, qint64 maxSize)
 {
+    //TODO: create a QByteArray from message, and directly call doWriteFrames
+    //now the data is converted to a string, and then converted back to a bytearray
     return write(QString::fromUtf8(message, static_cast<int>(maxSize)));
 }
 
@@ -169,7 +227,7 @@ qint64 QWebSocketPrivate::write(const char *message, qint64 maxSize)
  */
 qint64 QWebSocketPrivate::write(const QString &message)
 {
-    return doWriteData(message.toUtf8(), false);
+    return doWriteFrames(message.toUtf8(), false);
 }
 
 /*!
@@ -177,10 +235,52 @@ qint64 QWebSocketPrivate::write(const QString &message)
  */
 qint64 QWebSocketPrivate::write(const QByteArray &data)
 {
-    return doWriteData(data, true);
+    return doWriteFrames(data, true);
+}
+
+#ifndef QT_NO_SSL
+/*!
+    \internal
+ */
+void QWebSocketPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration)
+{
+    m_configuration.m_sslConfiguration = sslConfiguration;
+}
+
+/*!
+    \internal
+ */
+QSslConfiguration QWebSocketPrivate::sslConfiguration() const
+{
+    return m_configuration.m_sslConfiguration;
+}
+
+/*!
+    \internal
+ */
+void QWebSocketPrivate::ignoreSslErrors(const QList<QSslError> &errors)
+{
+    m_configuration.m_ignoredSslErrors = errors;
+}
+
+/*!
+ * \internal
+ */
+void QWebSocketPrivate::ignoreSslErrors()
+{
+    m_configuration.m_ignoreSslErrors = true;
+    if (m_pSocket) {
+        QSslSocket *pSslSocket = qobject_cast<QSslSocket *>(m_pSocket.data());
+        if (pSslSocket) {
+            pSslSocket->ignoreSslErrors();
+        }
+    }
 }
 
+#endif
+
 /*!
+  Called from QWebSocketServer
   \internal
  */
 QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
@@ -188,12 +288,12 @@ QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
                                            const QWebSocketHandshakeResponse &response,
                                            QObject *parent)
 {
-    QWebSocket *pWebSocket = new QWebSocket(pTcpSocket, response.getAcceptedVersion(), parent);
-    pWebSocket->d_func()->setExtension(response.getAcceptedExtension());
-    pWebSocket->d_func()->setOrigin(request.getOrigin());
-    pWebSocket->d_func()->setRequestUrl(request.getRequestUrl());
-    pWebSocket->d_func()->setProtocol(response.getAcceptedProtocol());
-    pWebSocket->d_func()->setResourceName(request.getRequestUrl().toString(QUrl::RemoveUserInfo));
+    QWebSocket *pWebSocket = new QWebSocket(pTcpSocket, response.acceptedVersion(), parent);
+    pWebSocket->d_func()->setExtension(response.acceptedExtension());
+    pWebSocket->d_func()->setOrigin(request.origin());
+    pWebSocket->d_func()->setRequestUrl(request.requestUrl());
+    pWebSocket->d_func()->setProtocol(response.acceptedProtocol());
+    pWebSocket->d_func()->setResourceName(request.requestUrl().toString(QUrl::RemoveUserInfo));
     //a server should not send masked frames
     pWebSocket->d_func()->enableMasking(false);
 
@@ -205,23 +305,22 @@ QWebSocket *QWebSocketPrivate::upgradeFrom(QTcpSocket *pTcpSocket,
  */
 void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString reason)
 {
-    Q_Q(QWebSocket);
-    if (!m_isClosingHandshakeSent)
-    {
+    if (!m_pSocket) {
+        return;
+    }
+    if (!m_isClosingHandshakeSent) {
+        Q_Q(QWebSocket);
         quint32 maskingKey = 0;
-        if (m_mustMask)
-        {
+        if (m_mustMask) {
             maskingKey = generateMaskingKey();
         }
         const quint16 code = qToBigEndian<quint16>(closeCode);
         QByteArray payload;
         payload.append(static_cast<const char *>(static_cast<const void *>(&code)), 2);
-        if (!reason.isEmpty())
-        {
+        if (!reason.isEmpty()) {
             payload.append(reason.toUtf8());
         }
-        if (m_mustMask)
-        {
+        if (m_mustMask) {
             QWebSocketProtocol::mask(payload.data(), payload.size(), maskingKey);
         }
         QByteArray frame = getFrameHeader(QWebSocketProtocol::OC_CLOSE, payload.size(), maskingKey, true);
@@ -241,38 +340,87 @@ void QWebSocketPrivate::close(QWebSocketProtocol::CloseCode closeCode, QString r
  */
 void QWebSocketPrivate::open(const QUrl &url, bool mask)
 {
-    m_dataProcessor.clear();
-    m_isClosingHandshakeReceived = false;
-    m_isClosingHandshakeSent = false;
-
-    setRequestUrl(url);
-    QString resourceName = url.path();
-    if (!url.query().isEmpty())
-    {
-        if (!resourceName.endsWith(QChar::fromLatin1('?')))
-        {
-            resourceName.append(QChar::fromLatin1('?'));
-        }
-        resourceName.append(url.query());
+    //m_pSocket.reset();  //just delete the old socket for the moment; later, we can add more 'intelligent' handling by looking at the url
+    QTcpSocket *pTcpSocket = m_pSocket.take();
+    if (pTcpSocket) {
+        releaseConnections(pTcpSocket);
+        pTcpSocket->deleteLater();
     }
-    if (resourceName.isEmpty())
-    {
-        resourceName = QStringLiteral("/");
+    //if (m_url != url)
+    if (!m_pSocket) {
+        Q_Q(QWebSocket);
+
+        m_dataProcessor.clear();
+        m_isClosingHandshakeReceived = false;
+        m_isClosingHandshakeSent = false;
+
+        setRequestUrl(url);
+        QString resourceName = url.path();
+        if (!url.query().isEmpty()) {
+            if (!resourceName.endsWith(QChar::fromLatin1('?'))) {
+                resourceName.append(QChar::fromLatin1('?'));
+            }
+            resourceName.append(url.query());
+        }
+        if (resourceName.isEmpty()) {
+            resourceName = QStringLiteral("/");
+        }
+        setResourceName(resourceName);
+        enableMasking(mask);
+
+    #ifndef QT_NO_SSL
+        if (url.scheme() == QStringLiteral("wss")) {
+            if (!QSslSocket::supportsSsl()) {
+                const QString message = tr("SSL Sockets are not supported on this platform.");
+                setErrorString(message);
+                emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
+            } else {
+                QSslSocket *sslSocket = new QSslSocket(this);
+                m_pSocket.reset(sslSocket);
+
+                makeConnections(m_pSocket.data());
+                connect(sslSocket, SIGNAL(encryptedBytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
+                setSocketState(QAbstractSocket::ConnectingState);
+
+                sslSocket->setSslConfiguration(m_configuration.m_sslConfiguration);
+                if (m_configuration.m_ignoreSslErrors) {
+                    sslSocket->ignoreSslErrors();
+                } else {
+                    sslSocket->ignoreSslErrors(m_configuration.m_ignoredSslErrors);
+                }
+#ifndef QT_NO_NETWORKPROXY
+                sslSocket->setProxy(m_configuration.m_proxy);
+#endif
+                sslSocket->connectToHostEncrypted(url.host(), url.port(443));
+            }
+        } else
+    #endif
+        if (url.scheme() == QStringLiteral("ws")) {
+            m_pSocket.reset(new QTcpSocket(this));
+
+            makeConnections(m_pSocket.data());
+            connect(m_pSocket.data(), SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
+            setSocketState(QAbstractSocket::ConnectingState);
+#ifndef QT_NO_NETWORKPROXY
+            m_pSocket->setProxy(m_configuration.m_proxy);
+#endif
+            m_pSocket->connectToHost(url.host(), url.port(80));
+        } else {
+            const QString message = tr("Unsupported websockets scheme: %1").arg(url.scheme());
+            setErrorString(message);
+            emit q->error(QAbstractSocket::UnsupportedSocketOperationError);
+        }
     }
-    setResourceName(resourceName);
-    enableMasking(mask);
-
-    setSocketState(QAbstractSocket::ConnectingState);
-
-    m_pSocket->connectToHost(url.host(), url.port(80));
 }
 
 /*!
     \internal
  */
-void QWebSocketPrivate::ping(const QByteArray &payload)
+void QWebSocketPrivate::ping(QByteArray payload)
 {
-    Q_ASSERT(payload.length() < 126);
+    if (payload.length() > 125) {
+        payload.truncate(125);
+    }
     m_pingTimer.restart();
     QByteArray pingFrame = getFrameHeader(QWebSocketProtocol::OC_PING, payload.size(), 0 /*do not mask*/, true);
     pingFrame.append(payload);
@@ -285,7 +433,9 @@ void QWebSocketPrivate::ping(const QByteArray &payload)
 */
 void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
 {
-    m_version = version;
+    if (m_version != version) {
+        m_version = version;
+    }
 }
 
 /*!
@@ -294,7 +444,9 @@ void QWebSocketPrivate::setVersion(QWebSocketProtocol::Version version)
 */
 void QWebSocketPrivate::setResourceName(const QString &resourceName)
 {
-    m_resourceName = resourceName;
+    if (m_resourceName != resourceName) {
+        m_resourceName = resourceName;
+    }
 }
 
 /*!
@@ -302,7 +454,9 @@ void QWebSocketPrivate::setResourceName(const QString &resourceName)
  */
 void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
 {
-    m_requestUrl = requestUrl;
+    if (m_requestUrl != requestUrl) {
+        m_requestUrl = requestUrl;
+    }
 }
 
 /*!
@@ -310,7 +464,9 @@ void QWebSocketPrivate::setRequestUrl(const QUrl &requestUrl)
  */
 void QWebSocketPrivate::setOrigin(const QString &origin)
 {
-    m_origin = origin;
+    if (m_origin != origin) {
+        m_origin = origin;
+    }
 }
 
 /*!
@@ -318,7 +474,9 @@ void QWebSocketPrivate::setOrigin(const QString &origin)
  */
 void QWebSocketPrivate::setProtocol(const QString &protocol)
 {
-    m_protocol = protocol;
+    if (m_protocol != protocol) {
+        m_protocol = protocol;
+    }
 }
 
 /*!
@@ -326,7 +484,9 @@ void QWebSocketPrivate::setProtocol(const QString &protocol)
  */
 void QWebSocketPrivate::setExtension(const QString &extension)
 {
-    m_extension = extension;
+    if (m_extension != extension) {
+        m_extension = extension;
+    }
 }
 
 /*!
@@ -334,15 +494,9 @@ void QWebSocketPrivate::setExtension(const QString &extension)
  */
 void QWebSocketPrivate::enableMasking(bool enable)
 {
-    m_mustMask = enable;
-}
-
-/*!
- * \internal
- */
-qint64 QWebSocketPrivate::doWriteData(const QByteArray &data, bool isBinary)
-{
-    return doWriteFrames(data, isBinary);
+    if (m_mustMask != enable) {
+        m_mustMask = enable;
+    }
 }
 
 /*!
@@ -350,18 +504,21 @@ qint64 QWebSocketPrivate::doWriteData(const QByteArray &data, bool isBinary)
  */
 void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
 {
+    Q_ASSERT(pTcpSocket);
     Q_Q(QWebSocket);
 
-    //pass through signals
-    connect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
-    connect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
-    connect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
-    connect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
-    //connect(pTcpSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
-
-    //catch signals
-    connect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
-    connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()));
+    if (pTcpSocket) {
+        //pass through signals
+        connect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
+        connect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
+        connect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
+        connect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
+
+        //catch signals
+        connect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
+        //!!!important to use a QueuedConnection here; with QTcpSocket there is no problem, but with QSslSocket the processing hangs
+        connect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()), Qt::QueuedConnection);
+    }
 
     connect(&m_dataProcessor, SIGNAL(textFrameReceived(QString,bool)), q, SIGNAL(textFrameReceived(QString,bool)));
     connect(&m_dataProcessor, SIGNAL(binaryFrameReceived(QByteArray,bool)), q, SIGNAL(binaryFrameReceived(QByteArray,bool)));
@@ -378,28 +535,10 @@ void QWebSocketPrivate::makeConnections(const QTcpSocket *pTcpSocket)
  */
 void QWebSocketPrivate::releaseConnections(const QTcpSocket *pTcpSocket)
 {
-    Q_Q(QWebSocket);
-    if (pTcpSocket)
-    {
-        //pass through signals
-        disconnect(pTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SIGNAL(error(QAbstractSocket::SocketError)));
-        disconnect(pTcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), q, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)));
-        disconnect(pTcpSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished()));
-        disconnect(pTcpSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose()));
-        //disconnect(pTcpSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64)));
-
-        //catched signals
-        disconnect(pTcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processStateChanged(QAbstractSocket::SocketState)));
-        disconnect(pTcpSocket, SIGNAL(readyRead()), this, SLOT(processData()));
+    if (pTcpSocket) {
+        disconnect(pTcpSocket);
     }
-    disconnect(&m_dataProcessor, SIGNAL(pingReceived(QByteArray)), this, SLOT(processPing(QByteArray)));
-    disconnect(&m_dataProcessor, SIGNAL(pongReceived(QByteArray)), this, SLOT(processPong(QByteArray)));
-    disconnect(&m_dataProcessor, SIGNAL(closeReceived(QWebSocketProtocol::CloseCode,QString)), this, SLOT(processClose(QWebSocketProtocol::CloseCode,QString)));
-    disconnect(&m_dataProcessor, SIGNAL(textFrameReceived(QString,bool)), q, SIGNAL(textFrameReceived(QString,bool)));
-    disconnect(&m_dataProcessor, SIGNAL(binaryFrameReceived(QByteArray,bool)), q, SIGNAL(binaryFrameReceived(QByteArray,bool)));
-    disconnect(&m_dataProcessor, SIGNAL(binaryMessageReceived(QByteArray)), q, SIGNAL(binaryMessageReceived(QByteArray)));
-    disconnect(&m_dataProcessor, SIGNAL(textMessageReceived(QString)), q, SIGNAL(textMessageReceived(QString)));
-    disconnect(&m_dataProcessor, SIGNAL(errorEncountered(QWebSocketProtocol::CloseCode,QString)), this, SLOT(close(QWebSocketProtocol::CloseCode,QString)));
+    disconnect(&m_dataProcessor);
 }
 
 /*!
@@ -453,56 +592,60 @@ QString QWebSocketPrivate::extension() const
 /*!
  * \internal
  */
-QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode, quint64 payloadLength, quint32 maskingKey, bool lastFrame) const
+QWebSocketProtocol::CloseCode QWebSocketPrivate::closeCode() const
+{
+    return m_closeCode;
+}
+
+/*!
+ * \internal
+ */
+QString QWebSocketPrivate::closeReason() const
+{
+    return m_closeReason;
+}
+
+/*!
+ * \internal
+ */
+QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode, quint64 payloadLength, quint32 maskingKey, bool lastFrame)
 {
     QByteArray header;
     quint8 byte = 0x00;
     bool ok = payloadLength <= 0x7FFFFFFFFFFFFFFFULL;
 
-    if (ok)
-    {
+    if (ok) {
         //FIN, RSV1-3, opcode
         byte = static_cast<quint8>((opCode & 0x0F) | (lastFrame ? 0x80 : 0x00));       //FIN, opcode
         //RSV-1, RSV-2 and RSV-3 are zero
         header.append(static_cast<char>(byte));
 
-        //Now write the masking bit and the payload length byte
         byte = 0x00;
-        if (maskingKey != 0)
-        {
+        if (maskingKey != 0) {
             byte |= 0x80;
         }
-        if (payloadLength <= 125)
-        {
+        if (payloadLength <= 125) {
             byte |= static_cast<quint8>(payloadLength);
             header.append(static_cast<char>(byte));
-        }
-        else if (payloadLength <= 0xFFFFU)
-        {
+        } else if (payloadLength <= 0xFFFFU) {
             byte |= 126;
             header.append(static_cast<char>(byte));
             quint16 swapped = qToBigEndian<quint16>(static_cast<quint16>(payloadLength));
             header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 2);
-        }
-        else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL)
-        {
+        } else if (payloadLength <= 0x7FFFFFFFFFFFFFFFULL) {
             byte |= 127;
             header.append(static_cast<char>(byte));
             quint64 swapped = qToBigEndian<quint64>(payloadLength);
             header.append(static_cast<const char *>(static_cast<const void *>(&swapped)), 8);
         }
 
-        //Write mask
-        if (maskingKey != 0)
-        {
-            header.append(static_cast<const char *>(static_cast<const void *>(&maskingKey)), sizeof(quint32));
+        if (maskingKey != 0) {
+            const quint32 mask = qToBigEndian<quint32>(maskingKey);
+            header.append(static_cast<const char *>(static_cast<const void *>(&mask)), sizeof(quint32));
         }
-    }
-    else
-    {
-        //setErrorString("WebSocket::getHeader: payload too big!");
-        //Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
-        qDebug() << "WebSocket::getHeader: payload too big!";
+    } else {
+        setErrorString(QStringLiteral("WebSocket::getHeader: payload too big!"));
+        Q_EMIT q_ptr->error(QAbstractSocket::DatagramTooLargeError);
     }
 
     return header;
@@ -513,32 +656,35 @@ QByteArray QWebSocketPrivate::getFrameHeader(QWebSocketProtocol::OpCode opCode,
  */
 qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
 {
+    qint64 payloadWritten = 0;
+    if (!m_pSocket) {
+        return payloadWritten;
+    }
     Q_Q(QWebSocket);
-    const QWebSocketProtocol::OpCode firstOpCode = isBinary ? QWebSocketProtocol::OC_BINARY : QWebSocketProtocol::OC_TEXT;
+    const QWebSocketProtocol::OpCode firstOpCode = isBinary ?
+                QWebSocketProtocol::OC_BINARY : QWebSocketProtocol::OC_TEXT;
 
     int numFrames = data.size() / FRAME_SIZE_IN_BYTES;
     QByteArray tmpData(data);
+    //TODO: really necessary?
     tmpData.detach();
     char *payload = tmpData.data();
-    quint64 sizeLeft = static_cast<quint64>(data.size()) % FRAME_SIZE_IN_BYTES;
-    if (sizeLeft)
-    {
+    quint64 sizeLeft = quint64(data.size()) % FRAME_SIZE_IN_BYTES;
+    if (sizeLeft) {
         ++numFrames;
     }
-    if (numFrames == 0)     //catch the case where the payload is zero bytes; in that case, we still need to send a frame
-    {
+    //catch the case where the payload is zero bytes;
+    //in this case, we still need to send a frame
+    if (numFrames == 0) {
         numFrames = 1;
     }
     quint64 currentPosition = 0;
     qint64 bytesWritten = 0;
-    qint64 payloadWritten = 0;
     quint64 bytesLeft = data.size();
 
-    for (int i = 0; i < numFrames; ++i)
-    {
+    for (int i = 0; i < numFrames; ++i) {
         quint32 maskingKey = 0;
-        if (m_mustMask)
-        {
+        if (m_mustMask) {
             maskingKey = generateMaskingKey();
         }
 
@@ -552,24 +698,18 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
         bytesWritten += m_pSocket->write(getFrameHeader(opcode, size, maskingKey, isLastFrame));
 
         //write payload
-        if (size > 0)
-        {
+        if (size > 0) {
             char *currentData = payload + currentPosition;
-            if (m_mustMask)
-            {
+            if (m_mustMask) {
                 QWebSocketProtocol::mask(currentData, size, maskingKey);
             }
             qint64 written = m_pSocket->write(currentData, static_cast<qint64>(size));
-            if (written > 0)
-            {
+            if (written > 0) {
                 bytesWritten += written;
                 payloadWritten += written;
-            }
-            else
-            {
-                setErrorString(tr("Error writing bytes to socket: %1.").arg(m_pSocket->errorString()));
-                qDebug() << errorString();
+            } else {
                 m_pSocket->flush();
+                setErrorString(tr("Error writing bytes to socket: %1.").arg(m_pSocket->errorString()));
                 Q_EMIT q->error(QAbstractSocket::NetworkError);
                 break;
             }
@@ -577,10 +717,8 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
         currentPosition += size;
         bytesLeft -= size;
     }
-    if (payloadWritten != data.size())
-    {
+    if (payloadWritten != data.size()) {
         setErrorString(tr("Bytes written %1 != %2.").arg(payloadWritten).arg(data.size()));
-        qDebug() << errorString();
         Q_EMIT q->error(QAbstractSocket::NetworkError);
     }
     return payloadWritten;
@@ -591,7 +729,7 @@ qint64 QWebSocketPrivate::doWriteFrames(const QByteArray &data, bool isBinary)
  */
 quint32 QWebSocketPrivate::generateRandomNumber() const
 {
-    return static_cast<quint32>((static_cast<double>(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
+    return quint32((double(qrand()) / RAND_MAX) * std::numeric_limits<quint32>::max());
 }
 
 /*!
@@ -609,9 +747,8 @@ QByteArray QWebSocketPrivate::generateKey() const
 {
     QByteArray key;
 
-    for (int i = 0; i < 4; ++i)
-    {
-        quint32 tmp = generateRandomNumber();
+    for (int i = 0; i < 4; ++i) {
+        const quint32 tmp = generateRandomNumber();
         key.append(static_cast<const char *>(static_cast<const void *>(&tmp)), sizeof(quint32));
     }
 
@@ -635,9 +772,11 @@ QString QWebSocketPrivate::calculateAcceptKey(const QString &key) const
 qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
 {
     qint64 written = 0;
-    for (int i = 0; i < frames.size(); ++i)
-    {
-        written += writeFrame(frames[i]);
+    if (m_pSocket) {
+        QList<QByteArray>::const_iterator it;
+        for (it = frames.cbegin(); it < frames.cend(); ++it) {
+            written += writeFrame(*it);
+        }
     }
     return written;
 }
@@ -647,7 +786,11 @@ qint64 QWebSocketPrivate::writeFrames(const QList<QByteArray> &frames)
  */
 qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
 {
-    return m_pSocket->write(frame);
+    qint64 written = 0;
+    if (m_pSocket) {
+        written = m_pSocket->write(frame);
+    }
+    return written;
 }
 
 /*!
@@ -655,18 +798,17 @@ qint64 QWebSocketPrivate::writeFrame(const QByteArray &frame)
  */
 QString readLine(QTcpSocket *pSocket)
 {
+    Q_ASSERT(pSocket);
     QString line;
-    char c;
-    while (pSocket->getChar(&c))
-    {
-        if (c == '\r')
-        {
-            pSocket->getChar(&c);
-            break;
-        }
-        else
-        {
-            line.append(QChar::fromLatin1(c));
+    if (pSocket) {
+        char c;
+        while (pSocket->getChar(&c)) {
+            if (c == char('\r')) {
+                pSocket->getChar(&c);
+                break;
+            } else {
+                line.append(QChar::fromLatin1(c));
+            }
         }
     }
     return line;
@@ -679,8 +821,7 @@ QString readLine(QTcpSocket *pSocket)
 void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
 {
     Q_Q(QWebSocket);
-    if (!pSocket)
-    {
+    if (!pSocket) {
         return;
     }
 
@@ -694,28 +835,22 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
     int httpStatusCode;
     QString httpStatusMessage;
     const QRegularExpressionMatch match = regExp.match(statusLine);
-    if (match.hasMatch())
-    {
+    if (match.hasMatch()) {
         QStringList tokens = match.capturedTexts();
         tokens.removeFirst();  //remove the search string
-        if (tokens.length() == 3)
-        {
+        if (tokens.length() == 3) {
             httpProtocol = tokens[0];
             httpStatusCode = tokens[1].toInt();
             httpStatusMessage = tokens[2].trimmed();
             ok = true;
         }
     }
-    if (!ok)
-    {
+    if (!ok) {
         errorDescription = tr("Invalid statusline in response: %1.").arg(statusLine);
-    }
-    else
-    {
+    } else {
         QString headerLine = readLine(pSocket);
         QMap<QString, QString> headers;
-        while (!headerLine.isEmpty())
-        {
+        while (!headerLine.isEmpty()) {
             const QStringList headerField = headerLine.split(QStringLiteral(": "), QString::SkipEmptyParts);
             headers.insertMulti(headerField[0], headerField[1]);
             headerLine = readLine(pSocket);
@@ -729,8 +864,8 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
         //const QString protocol = headers.value(QStringLiteral("Sec-WebSocket-Protocol"), QStringLiteral(""));
         const QString version = headers.value(QStringLiteral("Sec-WebSocket-Version"), QStringLiteral(""));
 
-        if (httpStatusCode == 101)     //HTTP/x.y 101 Switching Protocols
-        {
+        if (httpStatusCode == 101) {
+            //HTTP/x.y 101 Switching Protocols
             bool conversionOk = false;
             const float version = httpProtocol.midRef(5).toFloat(&conversionOk);
             //TODO: do not check the httpStatusText right now
@@ -738,54 +873,39 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
                    (!conversionOk || (version < 1.1f)) ||
                    (upgrade.toLower() != QStringLiteral("websocket")) ||
                    (connection.toLower() != QStringLiteral("upgrade")));
-            if (ok)
-            {
+            if (ok) {
                 const QString accept = calculateAcceptKey(QString::fromLatin1(m_key));
                 ok = (accept == acceptKey);
-                if (!ok)
-                {
+                if (!ok) {
                     errorDescription = tr("Accept-Key received from server %1 does not match the client key %2.").arg(acceptKey).arg(accept);
                 }
-            }
-            else
-            {
+            } else {
                 errorDescription = tr("QWebSocketPrivate::processHandshake: Invalid statusline in response: %1.").arg(statusLine);
             }
-        }
-        else if (httpStatusCode == 400)        //HTTP/1.1 400 Bad Request
-        {
-            if (!version.isEmpty())
-            {
+        } else if (httpStatusCode == 400) {
+            //HTTP/1.1 400 Bad Request
+            if (!version.isEmpty()) {
                 const QStringList versions = version.split(QStringLiteral(", "), QString::SkipEmptyParts);
-                if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion())))
-                {
+                if (!versions.contains(QString::number(QWebSocketProtocol::currentVersion()))) {
                     //if needed to switch protocol version, then we are finished here
                     //because we cannot handle other protocols than the RFC one (v13)
                     errorDescription = tr("Handshake: Server requests a version that we don't support: %1.").arg(versions.join(QStringLiteral(", ")));
                     ok = false;
-                }
-                else
-                {
+                } else {
                     //we tried v13, but something different went wrong
                     errorDescription = tr("QWebSocketPrivate::processHandshake: Unknown error condition encountered. Aborting connection.");
                     ok = false;
                 }
             }
-        }
-        else
-        {
+        } else {
             errorDescription = tr("QWebSocketPrivate::processHandshake: Unhandled http status code: %1 (%2).").arg(httpStatusCode).arg(httpStatusMessage);
             ok = false;
         }
 
-        if (!ok)
-        {
-            qDebug() << errorDescription;
+        if (!ok) {
             setErrorString(errorDescription);
             Q_EMIT q->error(QAbstractSocket::ConnectionRefusedError);
-        }
-        else
-        {
+        } else {
             //handshake succeeded
             setSocketState(QAbstractSocket::ConnectedState);
             Q_EMIT q->connected();
@@ -798,32 +918,30 @@ void QWebSocketPrivate::processHandshake(QTcpSocket *pSocket)
  */
 void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketState)
 {
+    Q_ASSERT(m_pSocket);
     Q_Q(QWebSocket);
     QAbstractSocket::SocketState webSocketState = this->state();
     switch (socketState)
     {
     case QAbstractSocket::ConnectedState:
     {
-        if (webSocketState == QAbstractSocket::ConnectingState)
-        {
+        if (webSocketState == QAbstractSocket::ConnectingState) {
             m_key = generateKey();
-            QString handshake = createHandShakeRequest(m_resourceName, m_requestUrl.host() % QStringLiteral(":") % QString::number(m_requestUrl.port(80)), origin(), QStringLiteral(""), QStringLiteral(""), m_key);
+            const QString handshake = createHandShakeRequest(m_resourceName, m_requestUrl.host() % QStringLiteral(":") % QString::number(m_requestUrl.port(80)), origin(), QStringLiteral(""), QStringLiteral(""), m_key);
             m_pSocket->write(handshake.toLatin1());
         }
         break;
     }
     case QAbstractSocket::ClosingState:
     {
-        if (webSocketState == QAbstractSocket::ConnectedState)
-        {
+        if (webSocketState == QAbstractSocket::ConnectedState) {
             setSocketState(QAbstractSocket::ClosingState);
         }
         break;
     }
     case QAbstractSocket::UnconnectedState:
     {
-        if (webSocketState != QAbstractSocket::UnconnectedState)
-        {
+        if (webSocketState != QAbstractSocket::UnconnectedState) {
             setSocketState(QAbstractSocket::UnconnectedState);
             Q_EMIT q->disconnected();
         }
@@ -859,15 +977,12 @@ void QWebSocketPrivate::processStateChanged(QAbstractSocket::SocketState socketS
  */
 void QWebSocketPrivate::processData()
 {
-    while (m_pSocket->bytesAvailable())
-    {
-        if (state() == QAbstractSocket::ConnectingState)
-        {
-            processHandshake(m_pSocket);
-        }
-        else
-        {
-            m_dataProcessor.process(m_pSocket);
+    Q_ASSERT(m_pSocket);
+    while (m_pSocket->bytesAvailable()) {
+        if (state() == QAbstractSocket::ConnectingState) {
+            processHandshake(m_pSocket.data());
+        } else {
+            m_dataProcessor.process(m_pSocket.data());
         }
     }
 }
@@ -877,16 +992,14 @@ void QWebSocketPrivate::processData()
  */
 void QWebSocketPrivate::processPing(QByteArray data)
 {
+    Q_ASSERT(m_pSocket);
     quint32 maskingKey = 0;
-    if (m_mustMask)
-    {
+    if (m_mustMask) {
         maskingKey = generateMaskingKey();
     }
     m_pSocket->write(getFrameHeader(QWebSocketProtocol::OC_PONG, data.size(), maskingKey, true));
-    if (data.size() > 0)
-    {
-        if (m_mustMask)
-        {
+    if (data.size() > 0) {
+        if (m_mustMask) {
             QWebSocketProtocol::mask(&data, maskingKey);
         }
         m_pSocket->write(data);
@@ -928,17 +1041,14 @@ QString QWebSocketPrivate::createHandShakeRequest(QString resourceName,
                         QStringLiteral("Upgrade: websocket") <<
                         QStringLiteral("Connection: Upgrade") <<
                         QStringLiteral("Sec-WebSocket-Key: ") % QString::fromLatin1(key);
-    if (!origin.isEmpty())
-    {
+    if (!origin.isEmpty()) {
         handshakeRequest << QStringLiteral("Origin: ") % origin;
     }
     handshakeRequest << QStringLiteral("Sec-WebSocket-Version: ") % QString::number(QWebSocketProtocol::currentVersion());
-    if (extensions.length() > 0)
-    {
+    if (extensions.length() > 0) {
         handshakeRequest << QStringLiteral("Sec-WebSocket-Extensions: ") % extensions;
     }
-    if (protocols.length() > 0)
-    {
+    if (protocols.length() > 0) {
         handshakeRequest << QStringLiteral("Sec-WebSocket-Protocol: ") % protocols;
     }
     handshakeRequest << QStringLiteral("\r\n");
@@ -959,7 +1069,11 @@ QAbstractSocket::SocketState QWebSocketPrivate::state() const
  */
 bool QWebSocketPrivate::waitForConnected(int msecs)
 {
-    return m_pSocket->waitForConnected(msecs);
+    bool result = false;
+    if (m_pSocket) {
+        result = m_pSocket->waitForConnected(msecs);
+    }
+    return result;
 }
 
 /*!
@@ -967,7 +1081,11 @@ bool QWebSocketPrivate::waitForConnected(int msecs)
  */
 bool QWebSocketPrivate::waitForDisconnected(int msecs)
 {
-    return m_pSocket->waitForDisconnected(msecs);
+    bool result = false;
+    if (m_pSocket) {
+        result = m_pSocket->waitForDisconnected(msecs);
+    }
+    return result;
 }
 
 /*!
@@ -976,8 +1094,7 @@ bool QWebSocketPrivate::waitForDisconnected(int msecs)
 void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
 {
     Q_Q(QWebSocket);
-    if (m_socketState != state)
-    {
+    if (m_socketState != state) {
         m_socketState = state;
         Q_EMIT q->stateChanged(m_socketState);
     }
@@ -988,7 +1105,9 @@ void QWebSocketPrivate::setSocketState(QAbstractSocket::SocketState state)
  */
 void QWebSocketPrivate::setErrorString(const QString &errorString)
 {
-    m_errorString = errorString;
+    if (m_errorString != errorString) {
+        m_errorString = errorString;
+    }
 }
 
 /*!
@@ -996,7 +1115,11 @@ void QWebSocketPrivate::setErrorString(const QString &errorString)
  */
 QHostAddress QWebSocketPrivate::localAddress() const
 {
-    return m_pSocket->localAddress();
+    QHostAddress address;
+    if (m_pSocket) {
+        address = m_pSocket->localAddress();
+    }
+    return address;
 }
 
 /*!
@@ -1004,7 +1127,11 @@ QHostAddress QWebSocketPrivate::localAddress() const
  */
 quint16 QWebSocketPrivate::localPort() const
 {
-    return m_pSocket->localPort();
+    quint16 port = 0;
+    if (m_pSocket) {
+        port = m_pSocket->localPort();
+    }
+    return port;
 }
 
 /*!
@@ -1012,7 +1139,11 @@ quint16 QWebSocketPrivate::localPort() const
  */
 QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
 {
-    return m_pSocket->pauseMode();
+    QAbstractSocket::PauseModes mode = QAbstractSocket::PauseNever;
+    if (m_pSocket) {
+        mode = m_pSocket->pauseMode();
+    }
+    return mode;
 }
 
 /*!
@@ -1020,7 +1151,11 @@ QAbstractSocket::PauseModes QWebSocketPrivate::pauseMode() const
  */
 QHostAddress QWebSocketPrivate::peerAddress() const
 {
-    return m_pSocket->peerAddress();
+    QHostAddress address;
+    if (m_pSocket) {
+        address = m_pSocket->peerAddress();
+    }
+    return address;
 }
 
 /*!
@@ -1028,7 +1163,11 @@ QHostAddress QWebSocketPrivate::peerAddress() const
  */
 QString QWebSocketPrivate::peerName() const
 {
-    return m_pSocket->peerName();
+    QString name;
+    if (m_pSocket) {
+        name = m_pSocket->peerName();
+    }
+    return name;
 }
 
 /*!
@@ -1036,47 +1175,63 @@ QString QWebSocketPrivate::peerName() const
  */
 quint16 QWebSocketPrivate::peerPort() const
 {
-    return m_pSocket->peerPort();
+    quint16 port = 0;
+    if (m_pSocket) {
+        port = m_pSocket->peerPort();
+    }
+    return port;
 }
 
+#ifndef QT_NO_NETWORKPROXY
 /*!
     \internal
  */
 QNetworkProxy QWebSocketPrivate::proxy() const
 {
-    return m_pSocket->proxy();
+    return m_configuration.m_proxy;
 }
 
 /*!
     \internal
  */
-qint64 QWebSocketPrivate::readBufferSize() const
+void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
 {
-    return m_pSocket->readBufferSize();
+    if (networkProxy != networkProxy) {
+        m_configuration.m_proxy = networkProxy;
+    }
 }
+#endif  //QT_NO_NETWORKPROXY
 
 /*!
     \internal
  */
-void QWebSocketPrivate::resume()
+qint64 QWebSocketPrivate::readBufferSize() const
 {
-    m_pSocket->resume();
+    qint64 size = 0;
+    if (m_pSocket) {
+        size = m_pSocket->readBufferSize();
+    }
+    return size;
 }
 
 /*!
-  \internal
+    \internal
  */
-void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
+void QWebSocketPrivate::resume()
 {
-    m_pSocket->setPauseMode(pauseMode);
+    if (m_pSocket) {
+        m_pSocket->resume();
+    }
 }
 
 /*!
-    \internal
+  \internal
  */
-void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
+void QWebSocketPrivate::setPauseMode(QAbstractSocket::PauseModes pauseMode)
 {
-    m_pSocket->setProxy(networkProxy);
+    if (m_pSocket) {
+        m_pSocket->setPauseMode(pauseMode);
+    }
 }
 
 /*!
@@ -1084,7 +1239,9 @@ void QWebSocketPrivate::setProxy(const QNetworkProxy &networkProxy)
  */
 void QWebSocketPrivate::setReadBufferSize(qint64 size)
 {
-    m_pSocket->setReadBufferSize(size);
+    if (m_pSocket) {
+        m_pSocket->setReadBufferSize(size);
+    }
 }
 
 /*!
@@ -1092,7 +1249,9 @@ void QWebSocketPrivate::setReadBufferSize(qint64 size)
  */
 void QWebSocketPrivate::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
 {
-    m_pSocket->setSocketOption(option, value);
+    if (m_pSocket) {
+        m_pSocket->setSocketOption(option, value);
+    }
 }
 
 /*!
@@ -1100,7 +1259,11 @@ void QWebSocketPrivate::setSocketOption(QAbstractSocket::SocketOption option, co
  */
 QVariant QWebSocketPrivate::socketOption(QAbstractSocket::SocketOption option)
 {
-    return m_pSocket->socketOption(option);
+    QVariant val;
+    if (m_pSocket) {
+        val = m_pSocket->socketOption(option);
+    }
+    return val;
 }
 
 /*!
@@ -1108,7 +1271,7 @@ QVariant QWebSocketPrivate::socketOption(QAbstractSocket::SocketOption option)
  */
 bool QWebSocketPrivate::isValid() const
 {
-    return m_pSocket->isValid();
+    return (m_pSocket && m_pSocket->isValid());
 }
 
 QT_END_NAMESPACE