本文主要是介绍QT 多线程使用QTcpSocket,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本人亲测使用moveToThread()的方式可以;不存在报错,警告#include "widget.h"
#include "ui_widget.h"Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);SocketThread *worker = new SocketThread;worker->moveToThread(&workerThread);connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);connect(this, &Widget::operate, worker, &SocketThread::run1);connect(worker, &SocketThread::resultReady, this, &Widget::handleResults);workerThread.start();emit operate();qDebug()<<"main"<<QThread::currentThreadId();
}Widget::~Widget()
{//t.exit();workerThread.quit();workerThread.wait();delete ui;
}void Widget::handleResults(const QString &)
{}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include"socketthread.h"
#include<QThread>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private:
Ui::Widget *ui;
QThread workerThread;
public slots:
void handleResults(const QString &);
signals:
void operate();
};
#endif // WIDGET_H
#include "socketthread.h"
#include"QDebug"
#include<QMessageBox>
#include<QThread>
SocketThread::SocketThread(QObject *parent) : QObject(parent)
{
//start();
}
SocketThread::~SocketThread()
{
// quit();
// wait();
}
void SocketThread::OnNewConnection()
{
qDebug()<<"new connection";
socket_ptr = std::make_shared<QTcpSocket>();
socket_ptr = static_cast<std::shared_ptr<QTcpSocket> >(server_ptr->nextPendingConnection());
connect(socket_ptr.get(),QTcpSocket::readyRead,this,OnRead);
socket_list->push_back(socket_ptr);
qDebug()<<QThread::currentThreadId();
}
void SocketThread::OnRead()
{
qDebug()<<"ready read";
qDebug()<<QThread::currentThreadId();
QByteArray arr;
QTcpSocket *socket_ptr = static_cast<QTcpSocket*>(sender());
arr = socket_ptr->readAll();
socket_ptr->write(arr);
qDebug()<<arr;
}
void SocketThread::run1()
{
socket_list = new std::list<std::shared_ptr<QTcpSocket>>();
server_ptr = std::make_shared<QTcpServer>();
server_ptr->listen(QHostAddress::Any,5000);
connect(server_ptr.get(),QTcpServer::newConnection,\
this,SocketThread::OnNewConnection);
qDebug()<<QThread::currentThreadId();
}
#ifndef SOCKETTHREAD_H
#define SOCKETTHREAD_H
#include <QObject>
#include <QTcpSocket>
#include<QTcpServer>
#include<memory>
#include<list>
class SocketThread : public QObject
{
Q_OBJECT
public:
explicit SocketThread(QObject *parent = 0);
~SocketThread();
signals:
public slots:
void OnNewConnection();
void OnRead();
public slots:
void run1();
private:
std::list<std::shared_ptr<QTcpSocket>> *socket_list;
std::shared_ptr<QTcpSocket> socket_ptr;
std::shared_ptr<QTcpServer> server_ptr;
signals:
void resultReady(const QString &result);
};
#endif // SOCKETTHREAD_H
这篇关于QT 多线程使用QTcpSocket的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!