Qt【WebSocket】建立一個簡單的websocket連線
1、使用說明
pro檔案中:
QT += websockets
C++類檔案中:
#include <QWebSocket>
2、客戶端的demo
該demo實現的功能:
1、建立webSocket連線;
2、連線中斷後,自動發起重連,週期為3秒。
這裡新建一個類,類名為DataReceive。
.h檔案
/**
* @breaf 用於建立websocket連線
* @note 該類實現了client端基本的websocket建立,自動重連。
* @author LittleMushroom
* date 2018年5月15日
*/
#ifndef DATARECEIVE_H
#define DATARECEIVE_H
#include <QtCore/QObject>
#include <QWebSocket>
#include <QString>
#include <QTimer>
class DataReceive : public QObject
{
Q_OBJECT
public:
DataReceive(QObject *parent=0);
~DataReceive();
public slots:
void createDataRecvWS(); /*-<建立websocket連線 */
private:
QWebSocket *dataRecvWS; /*-<websocket類 */
bool connectStatus; /*-<websocket連線狀態,連線成功:true;斷開:false */
void reconnect(); /*-<週期重連函式 */
QTimer *m_timer; /*-<週期重連Timer */
private slots:
void onConnected(); /*-<socket建立成功後,觸發該函式 */
void onTextReceived(QString msg); /*-<收到Sev端的資料時,觸發該函式 */
void onDisConnected(); /*-<socket連線斷開後,觸發該函式 */
};
#endif // DATARECEIVE_H
.cpp檔案
#include "datareceive.h"
#include <QDebug>
DataReceive::DataReceive(QObject *parent):QObject(parent)
{
dataRecvWS = Q_NULLPTR;
connectStatus = false;
m_timer = new QTimer();
}
DataReceive::~DataReceive(){
}
/**
* @breaf 建立WebSocket連線
*/
void DataReceive::createDataRecvWS(){
if(dataRecvWS == Q_NULLPTR){
dataRecvWS = new QWebSocket();
qDebug()<<"create websocket!";
connect(dataRecvWS,&QWebSocket::disconnected,this,DataReceive::onDisConnected,Qt::AutoConnection);
connect(dataRecvWS,&QWebSocket::textMessageReceived,this,DataReceive::onTextReceived,Qt::AutoConnection);
connect(dataRecvWS,&QWebSocket::connected,this,DataReceive::onConnected,Qt::AutoConnection);
connect(m_timer,m_timer->timeout,this,DataReceive::reconnect,Qt::AutoConnection);
dataRecvWS->open(QUrl("ws://192.168.0.17:60000/data"));
}
}
/**
* @breaf 判斷連線狀態
* @note 當連線成功後,觸發該函式
*/
void DataReceive::onConnected(){
qDebug()<<"DataReveive websocket is already connect!";
connectStatus = true;
m_timer->stop();
qDebug()<<"Address:"<<dataRecvWS->peerAddress();
}
/**
* @breaf 資料處理函式
* @param msg,資料資訊
* @note 當收到服務端傳送的資料時,觸發該函式
*/
void DataReceive::onTextReceived(QString msg){
qDebug()<<"----------------data-----------------";
qDebug()<<msg;
}
/**
* @breaf 連線斷開
* @note 當連線斷開時,觸發該函式
*/
void DataReceive::onDisConnected(){
qDebug()<<"DataReceive websocket is disconnected!!!";
connectStatus = false;
m_timer->start(3000);/*-<當連線失敗時,觸發重連計時器,設定計數週期為3秒 */
}
/**
* @breaf 週期重連函式
* @note 連線建立成功時,呼叫該函式
*/
void DataReceive::reconnect(){
qDebug()<<"try to reconnect!";
dataRecvWS->abort();
dataRecvWS->open(QUrl("ws://192.168.0.17:60000/data"));
}
main.cpp中的相關使用
DataReceive *m_dataReceive = new DataReceive();
m_dataReceive->createDataRecvWS();
---------------------
作者:踩星星的小蘑菇
來源:CSDN
原文:https://blog.csdn.net/dumuweiyang/article/details/80308431
版權宣告:本文為博主原創文章,轉載請附上博文連結!