Qt【WebSocket】创建一个简单的websocket连接

1、使用说明

pro文件中:

QT += websockets

C++类文件中:

#include 

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 
#include 
#include 
#include 

class DataReceive : public QObject
{
    Q_OBJECT
public:
    DataReceive(QObject *parent=0);
    ~DataReceive();

public slots:
    void createDataRecvWS();    /*-<创建websocket连接 */

private:
    QWebSocket *dataRecvWS;     /*-

.cpp文件

#include "datareceive.h"
#include 

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:"<peerAddress();


}

/**
 * @breaf 数据处理函数
 * @param msg,数据信息
 * @note  当收到服务端发送的数据时,触发该函数
 */
void DataReceive::onTextReceived(QString msg){
    qDebug()<<"----------------data-----------------";
    qDebug()<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();

你可能感兴趣的:(Qt,WebSocket,Qt,使用小结)