Question

i have created server and client to communication. Client sends binary data of image then server receives it and writes to file. I have pasted necessary code below.

            std::stringstream binStr;

            bytes_received = recv(new_sd, &binStr, sizeof(binStr) ,0);
            std::cout << binStr << std::endl;

            char buff[1024*1024];
            std::string image;

            while (!binStr.eof())
            {
                binStr.read(buff, sizeof (buff));
                image.append(buff, binStr.gcount());
            }

            int id = 1;
            std::stringstream ss2;
            ss2 << id;
            std::string str2 = ss2.str();
            std::ofstream img(str2.c_str(),std::ios::binary);
            std::cout << image.c_str() << std::endl;
            img.write(image.c_str(), image.length());

this code creates file with name as id , but its an empty file. How can i fix it?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top