Can't catch newConnection () signal from QTcpServer
I'm trying to do a simple server thread in QT to accept a connection, however, although the server is listening (I can connect to my test app), I can't get the newConnection () signal to take effect.
Any help on what I am missing here would be greatly appreciated!
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!
}
a source to share
First of all, I can say that your server lives in a new thread, while a CServerThread instance lives in a different thread (this instance was created in the thread). The Signal / slot connection you created calls inderect and uses the event stream to deliver events between event loops from two different threads. This can cause this problem if the thread in which you are creating the CServerThread does not have a Qt event loop.
I suggest you create some class MyServer that creates a QTcpServer and calls a listener and connects the QTcpServer :: newConnection () signal to its own slot. Then rewrite the method for starting the server thread to something like this:
void CServerThread::run() {
server = new MyServer(host,port);
exec(); // Start event loop
}
In this approach, the QTcpServer and newConnection processing objects are on the same thread. This situation is easier to handle.
I have one very simple working example:
Title: http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8h-example.html
Source: http://qremotesignal.googlecode.com/svn/tags/1.0.0/doc/html/hello_2server_2server_8cpp-example.html
a source to share