You cannot recv()
into a std::stringstream
like you are attempting to. You have to recv()
into a buffer first and then you can copy that data into your std::stringstream
afterwards. However, you are using the std::stringstream
only as an intermediate to get data into your buff
buffer, and then from there to a std::string
. You can get rid of the std::stringstream
altogether and recv()
directly into buff
instead. I would even go as far as getting rid of the std::string
altogether as well, as you do not really need it:
int id = 1;
std::stringstream ss2;
ss2 << id;
std::ofstream img(ss2.str().c_str(), std::ios::binary);
// 1MB is a lot to put on the stack, use the heap instead
std::vector<char> buff(1024*1024);
do
{
bytes_received = recv(new_sd, &buff[0], buff.size(), 0);
if (bytes_received < 0)
break; // ERROR!
if (bytes_received == 0)
break; // DISCONNECT!
for (int i = 0; i < bytes_received; ++i)
std::cout << buff[i];
std::cout << std::endl;
img.write(&buff[0], bytes_received);
// TODO: if reached the end of the image, stop here
}
while (true);
Unless the sender closes its end of the connection after sending the image data to you, then you need a way to know when the end of the image has been reached. The sender will have to send the image data length to you so you know when to stop reading.