I want to receive a request that is being sent in multiple chunks. In order to do so, I am using a TCP socket with recv. I loop over recv as follows:
while ((total_recv < MAX_HEADER) && (received = recv(client, req_buffer, CHUNK, 0)) > 0) {
total_recv += received;
if (strstr(req_buffer, delimiter) != NULL)
break;
}
My objective is to stop receiving when I have received the header whose end is marked by the delimiter. I am not guaranteed that the delimiter is present and so I break the loop if the total_recv is great or equal to the maximum known header size.
I do not like this. What bothers me is I can receive a packet with no delimiter that is smaller than the maximum header size. In this case I then have to assume that recv will continue to increment total_recv until the loop breaks. I know from reading the sockets API that recv will return the number of bytes read into the buffer, -1 on error, or 0 if the connection has been closed.
Is there a better way to loop on recv without relying on timeouts? What exactly are send() and recv() returning when a connection is open but not data is being transmitted by the sender or to the receiver?
CHUNK
then yourrecv
loop will read too much data once it reaches the end of the header. Also, your use ofstrstr()
is broken sincereq_buffer
is not null terminated, and you are not concatenating eachreq_buffer
received into an accumulated buffer on each loop iteration. – Remy Lebeau