I am currently programming a server in C that communicates over sockets using TCP. The client is supposed to send {filename\n} + {file contents\n} and the server will store that information and then send a response on success. However, we can't be sure the client will actually send the proper information in a structured protocol.
Often in simpler situations, we know a specified amount of bytes to be sent before and can wait until that specified number has been reached. In this case, we don't and currently the code looks like this:
//buffer is a resize-able array,
//assume it's correct + don't worry about memory leakage for now
resizeablearray_t *buffer;
char data[255];
char retry = 1;
while (retry) {
int bytes = read(socketfd, data, 255);
if (bytes <= 0) {
fprintf(stderr, "Error %s\n", strerror(errno));
return;
}
push(buffer, data, bytes);
}
Therefore, we're given a huge problem: how do we indicate to the read() function in c that we've read in all the information on the prior call and we shouldn't call it again?
The read() function blocks until there are bytes to be read over the server. However, in our model, if we continue to attempt to read due to short counts and there is nothing left in the buffer, we will wait FOREVER.
Any ideas on how to indicate before another read() call, without any prior information on the incoming message and its structure, that we can break from the while loop and stop attempting to read from the socket?