[Solved] Using QTcpSocket::write(QByteArray) several times - only sends the first time.
-
In my opinion better use request-response type communications. But correct me if i'm wrong :).
-
Tried to use waitForBytesWritten() after sending, no change.
Can you elaborate your second statement? Do you mean I should explicitely wait until I got a response until I send again?
-
The data is probably sent correctly, but the way your readNewData function is written means it can only treats one complete message.
As TCP and Qt doesn't guarantee that "1 sent message = 1 readyRead signal", you need to handle the cases where you don't receive a complete message, and where you receive several messages for the same signal.@void ClientConnection::readNewData() {
/* this has to be a class member, initialized to 0 when the connection opens /
/ quint16 blockSize = 0; */QDataStream in(_tcpSocket); in.setVersion(QDataStream::Qt_5_0); while(1) { if (blockSize == 0) { if (_tcpSocket->bytesAvailable() < (int)sizeof(blockSize)) return; in >> blockSize; } if (_tcpSocket->bytesAvailable() < blockSize) return; // read your message here // ... // reset for the next message blockSize = 0; }
}@
-
[quote author="Aerius" date="1360849229"]Do you mean I should explicitely wait until I got a response until I send again?[/quote]
Well, it is referred.
Look at incoming data probably you already read both messages at once.edit
As alexisdm already wrote :). -
[quote author="alexisdm" date="1360849664"]
As TCP and Qt doesn't guarantee that "1 sent message = 1 readyRead signal"
[/quote]Thank you, this was the core information I was missing. Your implementation also works perfectly, so thanks for that as well. :)
-
Look at "http://www.youtube.com/watch?v=BWEIWViWFwI&list=SP2D1942A4688E9D63&index=70":http://www.youtube.com/watch?v=BWEIWViWFwI&list=SP2D1942A4688E9D63&index=70
there is very good solution for client server apps. -
If you're passing a limited set of short messages, perhaps you can also consider using Qxt's RPC stuff. It allows you just use signals and slots across a network connection.
-
Seems Qxt is a really nice stuff. Andre have you try use any modules from it?
-
Yes, I have used it in the past.
-
Thanks for the tip Andre, I'll look into it. For the most part though, I'll be encoding and decoding objects of various sizes (see lines 36 to 41 in the second snip of code) and send them, so I guess the mechanism won't help me in that regard.
However, the mechanism sounds interesting, so maybe I can use that wherever I don't need to send whole objects across the network.