Answer the question
In order to leave comments, you need to log in
QTcpSocket::write() - how to guarantee data transfer in one packet?
Good afternoon.
I'm new to network programming, but still.
I am writing a client-server system. There is a qt client and a qt server. The client sends a request (json), the server processes the request and generates a json response.
On the server side, sending data is implemented through the socket-> write(data) method, where data is a string.
On the client side, when data is received, the slotReadyRead() method is called, connected to the readyRead() signal.
The data is read by the socket->readAll() method.
But here's the problem, when the server sends a small string, the client accepts it completely. If a large string (big Jason), then the string is transmitted in parts. That is, one call to the readyRead signal does not mean receiving a FULL message from the server, as far as I understand. Hence the question, how to transfer the ENTIRE LARGE string at once?
Answer the question
In order to leave comments, you need to log in
No way. TCP is a data stream , it is not broken into messages. When they are needed, they first pass the length, then the body of each next message.
No way. There is such a thing called MTU . The packet cannot be larger than the MTU in principle (usually it is about one and a half kilobytes).
In any case, you need a top-level protocol to communicate by messages and not by a stream (in principle, you can count the parentheses, of course, but this is not a solution). Often, a string is thrown between messages, which is guaranteed not to get into the data, or a size is passed before the message.
For a beginner, I would recommend qtWebsocket .
and it will not be transmitted completely, then what will change?
what will change is that you will know that the data has not yet arrived, and you need to read more.
Seriously - look at cutivebsockets, they are good friends with streams and there are 100 more pluses. I was once tempted to beat students hands for crooked solutions with raw-tcp.
Take a platform-independent data type. For example quint64.
Calculate message size, store in quint64.
Send this variable, then the message.
At the other end:
if(bytesAvailable() < sizeof(quint64)) return;
If more, read quint64, which will be the size of the next message. Well, we are waiting for the rest of the bytes to arrive, >= the received value.
And it is better to serialize data through QDataStream
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question