Qt - Handle QTcpSocket in a new thread

前端 未结 1 1611
面向向阳花
面向向阳花 2020-12-30 15:13

Trying to handle a connected client socket in a new thread from global thread pool:

m_threadPool = QThreadPool::globalInstance();

void TCPListenerThread::on         


        
相关标签:
1条回答
  • 2020-12-30 15:35

    I think this page holds your answer:

    If you want to handle an incoming connection as a new QTcpSocket object in another thread you have to pass the socketDescriptor to the other thread and create the QTcpSocket object there and use its setSocketDescriptor() method.

    To do this, you'll have to inherit from QTcpServer and override the virtual method incomingConnection.

    Within that method, create the child thread which will create a new QTcpSocket for the child socket.

    For example:

    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
        }
    };
    

    or try to use moveToThread() on the socket.

    0 讨论(0)
提交回复
热议问题