Qt WebSoket Ssl
#ifndef WEBSOCKETMANAGER_H
#define WEBSOCKETMANAGER_H
#include <QObject>
#include <QTimer>
#include <QWebSocket>
#include <QMutex>
#include "SslConfiguationTool.h"
/**
* @brief webSocket 连接管理类
*/
class WebSocketManager : public QObject
{
Q_OBJECT
public:
/**
* @brief 获取实例
* @return
*/
static WebSocketManager *getInstance();
/**
* @brief 连接服务器
* @param ip
* @param port
*/
void connectSer(const QString &ip, const int port);
private slots:
void onconnected();
void closeConnection();
void onTextMessageReceived(QString text);
void reconnect();
private:
explicit WebSocketManager(QObject *parent = nullptr);
static WebSocketManager *instance;
static QMutex mutex;
QWebSocket m_websocket;
int enableSsl = true;
};
#endif // WEBSOCKETMANAGER_H
#include "WebSocketManager.h"
WebSocketManager *WebSocketManager::instance = nullptr;
QMutex WebSocketManager::mutex;
WebSocketManager *WebSocketManager::getInstance()
{
if (!instance) {
QMutexLocker locker(&mutex);
if (!instance) {
instance = new WebSocketManager();
}
}
return instance;
}
void WebSocketManager::connectSer(const QString &ip, const int port)
{
qInfo() << Q_FUNC_INFO << ",ip:" << ip << ",port:" << port;
QString wsPath("ws://");
if (enableSsl) {
wsPath = "wss://";
}
wsPath.append(ip).append(":").append(QString::number(port, 10));
// 连接websocket
m_websocket.open(QUrl(wsPath));
}
void WebSocketManager::onconnected()
{
qInfo() << Q_FUNC_INFO;
}
void WebSocketManager::closeConnection()
{
qInfo() << Q_FUNC_INFO;
m_websocket.close();
}
void WebSocketManager::onTextMessageReceived(QString text)
{
qInfo() << Q_FUNC_INFO << ",text:" << text;
}
void WebSocketManager::reconnect()
{
qInfo() << Q_FUNC_INFO;
}
WebSocketManager::WebSocketManager(QObject *parent) : QObject(parent)
{
connect(&m_websocket, SIGNAL(connected()), this, SLOT(onconnected()));
connect(&m_websocket, SIGNAL(disconnected()),this, SLOT(closeConnection()));
connect(&m_websocket, SIGNAL(textMessageReceived(QString)), this, SLOT(onTextMessageReceived(QString)));
SslConfiguationTool::setSslConfiguation(m_websocket);
}
#ifndef SSLCONFIGUATIONTOOL_H
#define SSLCONFIGUATIONTOOL_H
#include <QWebSocket>
class SslConfiguationTool
{
public:
static void setSslConfiguation(QWebSocket &webSocket);
};
#endif // SSLCONFIGUATIONTOOL_H
#include "SslConfiguationTool.h"
void SslConfiguationTool::setSslConfiguation(QWebSocket &webSocket)
{
QSslConfiguration sslConf = webSocket.sslConfiguration();
sslConf.setPeerVerifyMode(QSslSocket::VerifyNone);
sslConf.setProtocol(QSsl::TlsV1SslV3);
webSocket.setSslConfiguration(sslConf);
}