cna cna - 3 months ago 7
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.

do
{
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);

FREE(buf);
buf = NULL;
}
while (chrs_read > 0);


So, sometime
chrs_read
doesn't return me
-1
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

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.

Solutions:

  • 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.
Comments