I seriously doubt the strcpy/strcat logic is what is tossing your performance, but it isn't needed, nor warranted. The follow continuously appends data directly to the response buffer, which is ever increasing with each iteration. Ideally this would grow geometric (e.g. the buffer space provided for the next read is compounded by the size already-read), but for this example a frame-by-frame solution will be sufficient.
Above all, this utilizes the return value of read
for what it is: a trio of error-announcement, end-of-data, or actual count of consumed octets. That is critical to remember when using read
. Anything greater than zero means we read something and anything less or equal to zero means no more data (0), or an error state (< 0) on a synchronous socket.
Anyway:
char *response = malloc(BUFFER_SIZE);
if (response)
{
ssize_t n = 0, size = 0;
while ((n = read(fd, response + size, BUFFER_SIZE-1)) > 0)
{
size += n; // accumulate data just-read
// make space for the next frame
void *tmp = realloc(response, size + BUFFER_SIZE);
if (tmp == NULL)
{
// failed to realloc. break now.
perror("Failed to realloc response buffer");
break;
}
// otherwise, retain new pointer and march on.
response = tmp;
}
// terminate the buffer. there will always be room
response[size] = 0;
// do with the response whatever you will.
fprintf(stderr, "%s", response);
free(response);
}
Something like that, anyway.
If that doesn't work, then the problem is in the IP stack on the client, the server, or the conduit in between.