PDA

View Full Version : QTcpSocket question, write method



Anslem
19th May 2014, 07:31
Hello,
I have a problem with QTcpSocket's "write" method.
I have a client and a server. Server tries to send some data to a client using the write function, it returns a correct number of bytes sent. But in reality, data is not sent, client can't read it. I tried to catch messages sent by server using WireShark and discovered that message is not sent, even though the write method does not return -1, it returns a correct number.

What could be a source of that error?

ChrisW67
19th May 2014, 09:18
You are probably not running a Qt event loop but since we cannot see your code we can only guess. QIODevice::write() returns the number of bytes written to the device. When the QIODevice is a socket the bytes will be sent over the wire at some time in the future by the asynchronous processing of the Qt event loop. If your code does not return to the Qt event loop the data is not sent.

Anslem
19th May 2014, 09:51
ChrisW6
Sorry for not posting a code before, it was a little bit complex. Anyway, your answer helped me. Here is something like the code i have now:


clientConnectionSocket->waitForReadyRead();
QByteArray data = clientConnectionSocket->readAll();
clientConnectionSocket->write("some data");
QTest::qWait(1000);


I added qWait to manually start event loop. Is it a bad solution?

ChrisW67
19th May 2014, 21:21
QTest is for testing so, yes, putting that in production code is not a good thing.
Qt networking works best when used through it asynchronous (normal, non-blocking) interface.
Qt network programming (http://qt-project.org/doc/qt-5/qtnetwork-programming.html#using-tcp-with-qtcpsocket-and-qtcpserver)
Network examples (http://qt-project.org/doc/qt-5/examples-network.html) especially the non-blocking fortune client.