标题:在线程中使用QTcpServer的问题
作者:xiongj2
日期:2019-11-08 09:08
内容:
本人近期在线程中使用QTcpServer发现无法进入QTcpServer::incomingConnection(qintptr)函数,也接收不到newConnection()信号。现将代码展示如下:
首先,声明TestThread类:
#pragma once
#include
#include
class TestThread : public QThread
{
Q_OBJECT
public:
TestThread(QObject *parent);
~TestThread();
voidstop();
protected:
voidrun();
private slots:
voidslotNewConnection();
private:
QTcpServer*m_pTcpServer;
boolm_bActive;
boolm_bStop;
};
该类的实现如下:
#include "testthread.h"
#include
TestThread::TestThread(QObject *parent)
: QThread(parent), m_pTcpServer(0), m_bActive(false), m_bStop(false)
{
}
TestThread::~TestThread()
{
stop();
}
voidTestThread::stop()
{
while (m_bActive)
{
m_bStop = true;
wait(200);
}
}
voidTestThread::run()
{
m_bStop = false;
m_bActive = false;
if (!m_pTcpServer)
{
m_pTcpServer = new QTcpServer();
QObject::connect(m_pTcpServer, SIGNAL(newConnection()),
this, SLOT(slotNewConnection()));
..
#1 [angelus 11-08 17:20]
这代码,我不想评论
#2 [圣域天子 11-08 18:19]
#3 回 angelus 的帖子 [xiongj2 11-09 09:25]
angelus:这代码,我不想评论 (2019-11-08 17:20)
我只是想用一段简单的代码来表达遇到的在线程中使用QTcpServer的问题,不过,我还是想拜读一下阁下史诗级般的著作。
#4 [明明越 11-09 09:46]
run函数一直死循环的话,run函数发出的信号不能进入 事件循环队列吧。
我写的TcpServer用的是movetothread方式,而且不要死循环,tcpserver初始化和调用也要在子线程内实现。
#5 回 明明越 的帖子 [xiongj2 11-09 10:01]
明明越:run函数一直死循环的话,run函数发出的信号不能进入 事件循环队列吧。
我写的TcpServer用的是movetothread方式,而且不要死循环,tcpserver初始化和调用也要在子线程内实现。 (2019-11-09 09:46)
牛!按你的方法解决了,在listen()后面加一行就OK了。m_pTcpServer->moveToThread(QApplication::instance()->thread());