Qt-在新螺纹中处理QTcpSocket

Qt - Handle QTcpSocket in a new thread

本文关键字:处理 QTcpSocket 新螺纹 Qt-      更新时间:2023-10-16

尝试在全局线程池的新线程中处理连接的客户端套接字:

m_threadPool = QThreadPool::globalInstance();
void TCPListenerThread::onNewConnection()
{
    QTcpSocket *clientSocket = m_tcpServer->nextPendingConnection();
    clientSocket->localPort();
    m_connectThread = new TCPConnectThread(clientSocket);
    m_threadPool->start(m_connectThread);
}

这是TCPConnectThread:

class TCPConnectThread : public QRunnable {
    TCPConnectThread::TCPConnectThread(QTcpSocket *_socket)
    {
        m_socket = _socket;
        this->setAutoDelete(false);
    }

    void TCPConnectThread::run()
    {
        if (! m_socket->waitForConnected(-1) )
            qDebug("Failed to connect to client");
        else
            qDebug("Connected to %s:%d %s:%d", m_socket->localAddress(), m_socket->localPort(), m_socket->peerAddress(), m_socket->peerPort());
        if (! m_socket->waitForReadyRead(-1))
            qDebug("Failed to receive message from client") ;
        else
            qDebug("Read from client: %s",   QString(m_socket->readAll()).toStdString().c_str());
        if (! m_socket->waitForDisconnected(-1))
            qDebug("Failed to receive disconnect message from client");
        else
            qDebug("Disconnected from client");
    }
}

我一直在犯这些错误。跨线程QTcpSocket处理似乎不可行(参见Michael的回答(。

一些错误:

QSocketNotifier: socket notifiers cannot be disabled from another thread  
ASSERT failure in QCoreApplication::sendEvent: "Cannot send events t objects owned by a different thread.  

我应该在另一个线程中处理QTcpSocket
如果我想在不同的线程中处理QTcpSocket,该怎么办
或者有没有办法从文件描述符创建QTcpSocket

我想这个页面包含了你的答案:

如果要将传入连接处理为新的QTcpSocket对象,则必须将socketDescriptor传递给其他线程,并在那里创建QTcpSocket对象,并使用其setSocketDescriptor((方法。

要做到这一点,您必须从QTcpServer继承并覆盖虚拟方法incomingConnection

在该方法中,创建将为子套接字创建新QTcpSocket的子线程。

例如:

class MyTcpServer : public QTcpServer
{
protected:
    virtual void incomingConnection(int socketDescriptor)
    {
         TCPConnectThread* clientThread = new TCPConnectThread(socketDescriptor);
         // add some more code to keep track of running clientThread instances...
         m_threadPool->start(clientThread);
    }
};
class TCPConnectThread : public QRunnable
{
private:    
    int m_socketDescriptor;
    QScopedPointer<QTcpSocket> m_socket;
public:
    TCPConnectionThread(int socketDescriptor)
        : m_socketDescriptor(socketDescriptor)
    {
        setAutoDelete(false);
    }
protected:    
    void TCPConnectThread::run()
    {
        m_socket.reset(new QTcpSocket());
        m_socket->setSocketDescriptor(m_socketDescriptor);
        // use m_socket
    }
};

或者尝试在套接字上使用moveToThread()