QT TCP客户端多线程

1、.h头文件

#ifndef MEASUREDATATHREAD_H
#define MEASUREDATATHREAD_H

#include
#include
#include
#include
#include
class MeasureDataThread : public QThread
{
    Q_OBJECT
public:
    MeasureDataThread(QObject *parent = 0);
    ~MeasureDataThread();
    bool connectHost();

protected:
    void run();
private slots:
    void receiveData();
    void slotDisconnected();
    void slotConnected();
    void slotTimeOut();
signals:
    void signMsg(QJsonObject json);
    void signClearMap();
private:
    QTcpSocket *m_socket;
    QTimer *m_timer;
    QString hostIp;
    int port;
    bool isConnected;

};

#endif // MEASUREDATATHREAD_H

 

2、.cpp文件

 

#include "MeasureDataThread.h"
#include
#include
#include
#include
MeasureDataThread::MeasureDataThread(QObject *parent):
    QThread(parent)
{
    this->moveToThread(this);
    QSettings read(qApp->applicationDirPath() + QString("/config.ini"),QSettings::IniFormat);
    hostIp = read.value("/addressIP/measure").toString();
    //   hostIp = QString("10.8.119.131");
    port = 8901;
    isConnected = false;
}

MeasureDataThread::~MeasureDataThread()
{
    delete m_socket;
}

void MeasureDataThread::run()
{
    m_socket = new QTcpSocket(this);
    m_timer = new QTimer(this);
    connect(m_socket,SIGNAL(readyRead()),this,SLOT(receiveData()));
    connect(m_socket,SIGNAL(disconnected()),this,SLOT(slotDisconnected()));
    connect(m_socket, SIGNAL(connected()), this, SLOT(slotConnected()));
    connect(m_timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
    connectHost();
    this->exec();

}

void MeasureDataThread::receiveData()
{
    QByteArray buffer = m_socket->readAll();
    qDebug()<     if(!buffer.contains("$$"))
        return;
    buffer.remove(buffer.length() - 2,2);
    QStringList jsonlist = QString(buffer).split("$$");
    qDebug()<     for(int i = 0; i     {
        QJsonObject jsonObject = QJsonDocument::fromJson(jsonlist[i].toLocal8Bit().data()).object();
        qDebug()<< jsonObject;
        emit signMsg(jsonObject);
    }
}

void MeasureDataThread::slotDisconnected()
{
    emit signClearMap();
    m_timer->start(2000);
    isConnected = false;
}

void MeasureDataThread::slotConnected()
{
    m_timer->stop();
    isConnected = true;
}

void MeasureDataThread::slotTimeOut()
{
    if (!isConnected)
    {
        qDebug()<< QString(tr("重新连接 %1 PLC从机服务器......")).arg(hostIp);
        connectHost();
    }
}

bool MeasureDataThread::connectHost()
{

    m_socket->abort();
    m_socket->connectToHost(hostIp,port);
    if(!m_socket->waitForConnected(2000))
    {
        qDebug()<         m_timer->start(2000);
        return false;
    }
    qDebug()<< QString(tr("连接 %1 服务器成功")).arg(hostIp);
    return true;
}
 

你可能感兴趣的:(QT TCP客户端多线程)