PDA

View Full Version : QTcpSocket, problems with readall()



Leo_san
28th September 2011, 22:47
Hello guys!
I got a big problem here. Im trying to send a large QString through QTcpSocket::write ... the "sender" side is going fine, this function returns exactly the number of bytes that i sent.
But on my server, i connected the signal "readyRead ()" to this function:


QString MainWindow::catchMessage(QTcpSocket *sock)
{
QString xmlMessage = sock->readAll();
xmlMessage.trimmed();
return xmlMessage;
}

It works, but only if the message got about 8000 of lenght. When i send more than 8000, the readAll() cant get the entire message.
When i make that:

QString MainWindow::catchMessage(QTcpSocket *sock)
{
QMessageBox::information(this,"msg", "Wasting Time");
QString xmlMessage = sock->readAll();
xmlMessage.trimmed();
return xmlMessage;
}

... the readAll can get all the msg. I think that's because the buffer is not complete when if i call "readAll()" right after the signal readyRead() is emited. The "human delay" (time it takes to the user click at "Ok" button on QMessageBox) is enough to the buffer charge all data.
But i dont want that msgbox here :[
If i do somthing like

while (somthing){
QString xmlMessage += sock->readAll(); }

the buffer stops to load the pending data... i must to do something that makes the main process to sleep (like msgbox) to give time enough to the buffer loads everything.
I know that's a stupid solution, but i dont know what to do to get all pices... i want somthing like

pleaseSocket_chargeAllData(socket);
QString msg = readAll(socket);

The signal "readyRead()" is emitted only once, don't matter the msg size.
I "googled" and tryied everything i saw but nothing is working for me. Please if somebody knows how to help me, reply!
Thanks!

Leonardo

oh, and sorry for my bad english... :D

wysota
28th September 2011, 23:37
You are incorrectly assuming that data sent in one piece will also arrive in one piece. TCP has no concept of records, pieces or messages. If you wish to detect the end of message, you have to know what to expect. A string can be of arbitrary size so you can never be sure no more data arrives in the next milisecond. If you are reading an xml document, you have to keep appending data to an internal buffer until you reach the end of the xml document. Then you can read the message from the buffer and do your work. Until then just keep appending to the buffer and wait for subsequent readyRead() signals.

Leo_san
29th September 2011, 00:31
Thanks man problem solved!!!
I didn't know that lots of "readyRead()" was emitted, one for every piece buffered.
That was for my college work tomorrow. Thanks a lot!!