1

我已经创建了服务器和客户端进行通信。客户端发送图像的二进制数据,然后服务器接收它并写入文件。我在下面粘贴了必要的代码。

            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());

此代码创建名称为 id 的文件,但它是一个空文件。我该如何解决?

4

1 回答 1

1

你不能recv()变成std::stringstream你想要的样子。您必须先recv()进入缓冲区,然后才能将该数据复制到您的缓冲区中std::stringstream。但是,您使用std::stringstreamonly 作为将数据放入buff缓冲区,然后从那里到std::string. 你可以完全摆脱std::stringstream掉,recv()直接进入buff。我什至会完全摆脱std::string它,因为你并不真正需要它:

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);

除非发送方在将图像数据发送给您后关闭其连接末端,否则您需要一种方法来知道何时到达图像末端。发件人必须将图像数据长度发送给您,以便您知道何时停止阅读。

于 2014-01-24T21:09:14.600 回答