2010-05-12 103 views
2

我試圖使QT一個簡單的服務器線程接受連接趕上newConnection()信號,然而儘管服務器監聽(我可以用我的測試應用程序連接),我不能讓newConnection()信號起作用。無法從QTcpServer既可

任何幫助,因爲我在這裏失蹤將不勝感激!


class CServerThread : public QThread 
{ 
    Q_OBJECT 

protected: 
    void run(); 

private: 
    QTcpServer* server; 

public slots: 
    void AcceptConnection(); 
}; 


void CServerThread::run() 
{ 
    server = new QTcpServer; 

    QObject::connect(server, SIGNAL(newConnection()), this, SLOT(AcceptConnection())); 

    server->listen(QHostAddress::Any, 1000); // Any port in a storm 

    exec(); // Start event loop 
} 


void CServerThread::AcceptConnection() 
{ 
    OutputDebugStringA("\n***** INCOMING CONNECTION"); // This is never called! 
} 

回答

2

首先,我可以說你的服務器住在新的線程中,而CServerThread實例存在於另一個線程中(在線程創建的線程中)。您正在創建的信號/插槽連接不正確,並且在兩個不同線程的事件循環之間使用線程保存事件傳遞。如果創建CServerThread的線程沒有運行Qt事件循環,它實際上會導致這樣的問題。

我建議你創建一些MyServer類,它創建QTcpServer並調用listen並將QTcpServer :: newConnection()信號連接到它自己的插槽。然後重寫你的服務器線程的run方法去是這樣的:

void CServerThread::run() { 
    server = new MyServer(host,port); 
    exec(); // Start event loop 
} 

在這種方法既QTcpServer既可和newConnection處理對象的生活在同一個線程。這種情況更容易處理。

我有一個非常簡單的工作例如:

頁眉:http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8h-example.html

來源:http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8cpp-example.html

+0

非常感謝,我將這個返工的建議。 – Bob 2010-05-12 15:52:56

相關問題