views:

89

answers:

1

I am trying to make a simple server thread in QT to accept a connection, however although the server is listening (I can connect with my test app) I can't get the newConnection() signal to be acted on.

Any help as to what I'm missing here would be much 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!
}
+2  A: 

First of all I can say that your server lives in new thread while CServerThread instance lives in another thread (in the thread this instance was created). Signal/slot connection you are creating is inderect and uses thread save event delivery between events loops of two different threads. It actually can cause such problem if thread where you creating CServerThread doesn't have Qt event loop running.

I suggest you to create some MyServer class which creates QTcpServer and calls listen and connects QTcpServer::newConnection() signal to its own slot. Then rewrite your server thread run method to something like this:

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

In this approach both QTcpServer and newConnection processing object lives in the same thread. Such situation is easier to handle.

I have one really simple working example:

Header: 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

VestniK
Thanks very much, I'll rework this as suggested.
Bob