以前都是重写的方式来写线程,后来发现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线程的方法
以上代码仅展示方法,不能完全移植 编译 运行,如要使用,亲酌情修改!!!