QTcpServer在QRunnable工作时没有收到任何数据 [英] QTcpServer not receiving any data when working in QRunnable

查看:522
本文介绍了QTcpServer在QRunnable工作时没有收到任何数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的是一个奇怪的问题在典型的情况下:QTcpServer的方法incomingConnection在自定义类中被覆盖,任何接收的连接计划在QThreadPool的单独的线程中处理。

What I'm having is a strange problem in typical scenario: QTcpServer's method incomingConnection is overrided in custom class, and any received connection is planned for processing in separate thread on QThreadPool.

服务器:

void FooS::incomingConnection(qintptr socketDescriptor)
{

    QThreadPool *thread_pool = QThreadPool::globalInstance();
    FooSocket *fs = new FooSocket();
    fs->setSocket(socketDescriptor);
    thread_pool->start(fs);
}

任务:

class FooSocket: public QObject, public QRunnable;
...
private slots:
   void connectionIncomingData();
...
void FooSocket::run() {
    QTcpSocket *socket = new QTcpSocket();
    qDebug() << "SD: " << socketDescriptor; // is correct
    if (!socket->setSocketDescriptor(socketDescriptor)) {
        qDebug() << "Can't set socket descriptor";
        emit error(socket->error());
        return;
    }
//  -- had no effect here
// socket->moveToThread(QThread::currentThread()); 

    connect(socket, SIGNAL(readyRead()), this, SLOT(connectionIncomingData()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(connectionClosed()));    

}

readyRead信号不会被触发,确认(tcpdump)发送数据。

readyRead signal doesn't gets triggered, but socket client is confirmed (tcpdump) to send data..

使QRunnable生成一个带有套接字逻辑的QThread对象,并使用setAutoDelete,moveToThread - p>

After making QRunnable to spawn a QThread object with socket logics inside, and toying with setAutoDelete, moveToThread - still no effect.

推荐答案

为了处理 QRunnable 中的事件,它自己的事件循环,它不能依赖于主线程中的一个。

In order to process events in a QRunnable, a thread needs to have its own event loop, it mustn't rely on the one from the main thread. From what you've shown in your code, your thread quickly starts, then exits without running a loop.

尝试添加

QEventLoop loop;

// connect a signal to the event loop's quit() slot

loop.exec();

这篇关于QTcpServer在QRunnable工作时没有收到任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆