PDA

View Full Version : problems using QTcpSocket



HERC
12th February 2010, 16:41
Hello,

I want to implement a TCP client connection that can recieve messages and reponses. For that I use a Qqueue for putting the response of my request and I use the readyRead signal to see if there are incoming response/requests.

My code looks as follows



connect(tcpSocket,SIGNAL(readyRead()),this, SLOT(readData()));

......

response_ptr Client:: sendRequest(QByteArray const &data) {

qDebug() << "Request: " << data.constData();
tcpSocket->write(data);
while(response_queue.isEmpty()) {}
return response_ptr(response_queue.dequeue());

}

void Client::readData() {

.....
// Read response an put it on the queue

response_queue.queue(response)
}

.....


if I run the code and call "sendRequest", I come into a loop. Using wireShark I see that the request isn't send to the server.It seems that QT doesn't create a thread for listening to incoming data. I think that everything is running on the same thread ? So do I need to create a thread for listening on incoming messages/ responses ?

^NyAw^
12th February 2010, 16:49
Hello,



while(response_queue.isEmpty()) {}
return response_ptr(response_queue.dequeue());



I think that this is a programming error. The "return" statment exits the function, you don't get a while loop as it have returned to the caller instruction.

HERC
12th February 2010, 17:03
Hello,





On line 8 I put some data on the socket. But it seems that it is not send to the server. On line 9 I come into an endless loop, since I don't recieve any responses. If I delete line 9, then te message is send to the server and I recieve a response.

^NyAw^
12th February 2010, 17:35
Hi,

Try this:

^NyAw^
12th February 2010, 17:35
Hi,

Try this:


tcpSocket->write(data);
tcpSocket->flush;

HERC
12th February 2010, 19:53
Using
tcpSocket->flush(); it still not works.

faldzip
13th February 2010, 01:25
you have to divide sending and receiving. In sendRequest() just send your data and return. QTcpSocket works in asynchronous mode so it will inform you with a signal about incoming data. But doing

while (sth) { }
just block event loop so I guess it won't work at all.
Just return and happily wait for readyRead(). Make a signal in your class and emit it when response is ready (so after reading it from socket after readyRead()).