[Qt-interest] problem using sockets and threads
pmqt71
pmqt71 at gmail.com
Tue Feb 8 15:40:06 CET 2011
Hi,
I'm writing a client server app and have a problem on the server side.
Like a producer/consumer pattern, the server creates 1 thread for each
connected socket/client and 1 consumer thread to manage the requests.
The problem is that at one point the socket readyRead signal (server
side) is not fired anymore. These are the steps:
1) ClientConnectionThread runs on the server side and handles a client
socket (one instance per connected client). In the run method I
connect the readyRead signal and then call exec().
2) a client connects and sends a request
3) ClientConnectionThread::onReadyRead is invoked, reads the request,
puts it in a queue (a mutex protects append/dequeue) and wakes the
ConsumerThread.
4) ConsumerThread gets the request from the queue, processes it and
answers to the client posting a custom event (having the answer as
data member) on the ClientConnectionThread
5) ClientConnectionThread gets the custom event in the event method,
gets the answer and write it to the connected socket.
-- this request/response is OK --
6) Just after the ConsumerThread must send data to the connected
client (there is no request from the client), again posting a custom
event with associated data to the ClientConnectionThread
7) ClientConnectionThread gets the custom event with the data and
writes to the connected socket.
8) the client receives the data correctly, all seems OK.
Now the problem: if the client sends a request to the server,
ClientConnectionThread::onReadyRead is not fired. It seems that the
ClientConnectionThread event loop is not running properly.
Is there something wrong (or all) in the design causing a problem in the thread?
same code:
void ClientConnectionThread::run()
{
m_tcpSocket = new QTcpSocket();
if (!m_tcpSocket->setSocketDescriptor(m_socketDescriptor)) {
emit error(m_tcpSocket->error());
return;
}
connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(m_tcpSocket, SIGNAL(disconnected()), this,
SLOT(onSocketDisconnect()));
exec();
}
bool ClientConnectionThread::event(QEvent *ev)
{
if(ev->type() == QDataEvent::DataEventType)
{
QDataEvent *dataEvent = static_cast<QDataEvent *>(ev);
//only this thread handles the socket
writeToSocket(m_tcpSocket, dataEvent->data().toString());
}
return QThread::event(ev);
}
More information about the Qt-interest-old
mailing list