Search code examples
c++qtsocketstcpdelay

Qt TcpSockets - multiple sends being recieved at once


Using TCP Sockets, my client/server has a situation where messages are being sent from the client, and the server is receiving and writing them to file. The problem im running into is for some reason even though I have the messages being split up, they are all being recieved on one line.

So for example.. say im sending a text file line by line using:

socket->write(msg.toUtf8().constData());
    socket->waitForBytesWritten(5000);

The server sometimes receives multiple messages all in one receive.

So if the text file said:

hello,

this is the client

Sometimes the server will receive "hello this is the client", receiving both messages together when they should have been separate.

Someone might say i coded it wrong then, but the weird thing is, if i test the client/server locally, it all works perfect. As soon as i do it over a network this problem starts to happen. I did some testing adding in delays between sending messages. This also fixed the problem, but only after I increased the delays to nearly 1 second per message. This is a problem if a large number of messages need to be sent, 1 second each eventually takes a long time.


Solution

  • Remember that TCP is a streaming protocol. There are no natural message boundaries, data is just a stream of bytes.

    If you want messages to be separated, you have to add a protocol on top of TCP which includes these boundaries. For text, newlines are a natural boundary and are used in many text-based protocols.