Reputation: 122
I have a client/server application in C++. The server sends a rather large file(27KB) to the client. The client reads from the socket fixed length of 1024 bytes, which I then concatenate to a string. However, when I use the += operator, it doesn't seem to allocate more than 4048 bytes and I end up with a 4KB file on the clients side.
Clients code:
#define BUFFER_SIZE 1024
string outStr="";
char buf[BUFFER_SIZE];
while(1){
int numread;
if ((numread = read(clientSocket, buf, sizeof(buf) -1)) == -1){
fprintf(stderr,"Error: reading from socket");
exit(1);
}
fprintf(stderr,"received answer with numread: %d\n",numread);
if (numread == 0){
break;
}
buf[numread] = '\0';
outStr+=buf;
}
fprintf(stderr,"Transmission is over with total length: %d\n",outStr.length());
The output i get is:
26 times:
received answer with numread: 1023
and after that:
received answer with numread: 246
received answer with numread: 0
transmission is over with total length: 4048
The outputs confirms that the whole file is transferred, but the concatenation does not let me append over the (system limit?) of 4048. However, the c++ string should automatically reallocate its memory when the content needs to be larger. So why is this happening?
Thank you for answers.
Upvotes: 1
Views: 273
Reputation: 9696
You could use str::append (overload no. 4) and explicitly provide the number of bytes to append. This will then properly also append null bytes. So, instead of:
buf[numread] = '\0';
outStr+=buf;
do
outStr.append(numread, buf);
Upvotes: 2
Reputation: 167
Strings end at '\0' so if your byte array from the socket has something like that, when you concatenate at the end of your response string it will only concatenate until that point. So I think you should use a std::vector to store the whole response.
Upvotes: 0