The issue is most likely that you sent binary data. And binary data can contain zeros. And zeroes are the normal string terminator.
This means that when you do temp.str(Rbuffer)
(assuming temp
is a std::stringstream
) then it only gets data from Rbuffer
until the first zero.
Instead of using e.g. std::stringstream
use std::string
:
while(strBuffer.length() < fileSize)
{
char buffer[2048];
ssize_t n = read(sockets.newsockfd, buffer, sizeof(buffer));
if (n <= 0)
{
// An error, or connection closed
if (n < 0)
error("ERROR reading from socket");
break;
}
// Create a string of `n` bytes, including possible string terminators
// and add it to out current buffer
strBuffer += std::string(buffer, n);
}
The important thing to remember here is that you can't use the received data as a string! If it's binary data it will with most certainty contain the string terminator and so you have to treat is as binary data and not a string (even though you can store it in a std::string
).
You also need to be aware that you can't print the data, as many binary values are either unprintable or will print as "garbage".
And lastly, if you read and write binary files, you need to open them in binary modes, or you will get errors with the bytes 0x0d
and 0x0a
(i.e. carriage-return and newline).