qt 线程 moveToThread

以前都是重写的方式来写线程,后来发现moveToThread的方式也很好用
tcppth.h

#ifndef TCPPTH_H
#define TCPPTH_H

#include <QObject>
#include <QDebug>
#include <QTcpSocket>
#include <QString>
#include <QByteArray>
#include "protocal.h"
#include <QThread>
#include "attctrlpth.h"

class tcpPth : public QObject
{
    Q_OBJECT
public:
    tcpPth();
    ~tcpPth();
    void init(QString ip, int port);
    void tcpStart();
    void tcpClose();
    protocal *P;

protected slots:
    void tcp_read();

signals:


private:
    QTcpSocket *tcpSocket;
    QString IP;
    QString PORT;

    QThread *pth;
};

#endif // TCPPTH_H

tcppth.cpp

#include "tcppth.h"

tcpPth::tcpPth()
{
    P = new protocal();
    pth = new QThread();
    tcpSocket = new QTcpSocket(this);
}

tcpPth::~tcpPth()
{

    tcpSocket->close();
    pth->quit();
    pth->wait();
    pth->deleteLater();
}

void tcpPth::init(QString ip, int port)
{

    tcpSocket->connectToHost(ip, port,QTcpSocket::ReadWrite);
    if(!tcpSocket->waitForConnected())
    {
        qDebug()<<"client connect error:"<<ip<<":"<<port;
    }
    else
    {
        qDebug()<<"已连接上";
 
        connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(tcp_read()), Qt::QueuedConnection);
    }

}

void tcpPth::tcp_read()
{
    QByteArray array = tcpSocket->readAll();
//    qDebug("size:%d", array.size());
    P->loop_run((uint8_t*)array.data(), array.size());

}


void tcpPth::tcpStart()
{
    this->moveToThread(pth);
    tcpSocket->moveToThread(pth);
    pth->start();
}

void tcpPth::tcpClose()
{
    pth->quit();
    pth->wait();
    pth->deleteLater();
//    tcpSocket->disconnected();
}

调用方法:

tcpFly = new tcpPth();
tcpFly->init(qip, qport.toInt());
tcpFly->tcpStart();

这是一个tcp moveToThread线程的方法
以上代码仅展示方法,不能完全移植 编译 运行,如要使用,亲酌情修改!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值