接收二进制数据和写入(C ++中的套接字编程)

时间:2014-01-24 16:34:24

标签: c++ sockets tcp binary sstream

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

            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的文件,但它是一个空文件。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您不能像recv() std::stringstream那样尝试recv()。您必须首先std::stringstream进入缓冲区,然后您可以将该数据复制到std::stringstream。但是,您仅将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); 。我甚至可以完全摆脱{{1}},因为你真的不需要它:

{{1}}

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