【问题标题】:QTcpServer not receiving any data when working in QRunnable在 QRunnable 中工作时 QTcpServer 未收到任何数据
【发布时间】:2013-12-17 18:11:24
【问题描述】:

我在典型场景中遇到了一个奇怪的问题:QTcpServer 的方法incomingConnection 在自定义类中被覆盖,并且任何接收到的连接都计划在 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)发送数据..

在使 QRunnable 生成一个内部带有套接字逻辑的 QThread 对象,并玩弄 setAutoDelete、moveToThread 之后 - 仍然没有效果。

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    为了处理QRunnable 中的事件,线程需要有自己的事件循环,它不能依赖主线程中的事件循环。根据您在代码中显示的内容,您的线程快速启动,然后在不运行循环的情况下退出。

    尝试添加

    QEventLoop loop;
    
    // connect a signal to the event loop's quit() slot
    
    loop.exec();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      相关资源
      最近更新 更多