Tcp packets using QTcpSocket

I know that TCP ensures that all packets arrive. But can a package be divided into 2 or more? I use Qt with the QTcpSocket class, and I want to know that the ReadyRead signal is emitted only when a full packet is received. Or, in other words, does it make sense to send the packet size in the first bytes, and then wai in a loop until all bytes are received? Or can I just call socket-> readAll () and should I get one complete package?

+1
source share
1 answer

If a large amount of data is sent, the packet may arrive in separate parts. Alternatively, multiple messages can be received in one readyRead slot.

It is good practice to control this by setting the first byte (s) to the number of bytes to be sent. Then in readyRead you read the first bytes and add data to the buffer until the expected amount of data is received.

When receiving data, this also means that if several messages are received in one readyRead () call, you can find out where the first message ends and the next begins.

Here is an example of a client that receives data in the readyRead () function

void MyClass::readyRead() { // m_pConnection is a QTcpSocket while(m_pConnection->bytesAvailable()) { QByteArray buffer; int dataSize; m_pConnection->read((char*)&dataSize, sizeof(int)); buffer = m_pConnection->read(dataSize); while(buffer.size() < dataSize) // only part of the message has been received { m_pConnection->waitForReadyRead(); // alternatively, store the buffer and wait for the next readyRead() buffer.append(m_pConnection->read(dataSize - buffer.size())); // append the remaining bytes of the message } QString msg(buffer); // data in this case is JSON, so we can use a QString emit Log(QString("\tMessage Received: %1").arg(msg)); // Do something with the message ProcessMessage(msg); } } 
+8
source

Source: https://habr.com/ru/post/1207733/


All Articles