cna cna - 1 year ago 79
C++ Question

Concatenating buffer when the sending is too fast in a socket

I have a socket server receiving XML files each 500ms and sometimes it goes wrong concatenating more than 1 file as only one file.

char* buf = (char*)MALLOCZ(IP_BUF_SZ);
chrs_read = recv(sockfd, buf, IP_BUF_SZ, 0);

if (chrs_read > 0)
sBuffer.append(buf, chrs_read);

buf = NULL;
while (chrs_read > 0);

So, sometime
doesn't return me
to stop the receiving and save the file to start a new receiving.
Do I forget some configuration in the socket - it's async and non-blocking by default - and I supposed to keep using this way?
Thank you in advance

Answer Source

The problem is that all files are sent through the same connection, without having a delimiter between them. When the files are sent often, and there is some latency in the network, you can't know where a file ends and a new one begins.


  • Insert a delimiter between the files, such that you can close the file when you receive the delimiter, and open a new one. Note that the delimiter may be received anywhere inside of buf, or it could even, if the delimiter is longer than one byte, be received partially in one recv call, and the rest follows in the next recv call.
  • On the sending end, close the connection after sending the file and open a new one for the new file.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download