gpt4 book ai didi

c++ - 使用 boost iostream socket 读写文件

转载 作者:太空狗 更新时间:2023-10-29 21:14:46 26 4
gpt4 key购买 nike

我正在尝试使用 boost iostream 套接字发送和接收文件。读取文件内容然后发送到流的最有效方法是什么?以及如何在服务器端读取这些内容并写入文件?

发送:

boost::asio::io_service svc;
using boost::asio::ip::tcp;
tcp::iostream sockstream(tcp::resolver::query{ "127.0.0.1", "3780" });

std::ifstream fs;
fs.open("img.jpg", std::ios::binary);
sockstream << // send file to stream

接收:

boost::asio::io_service ios;

boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 3780);
boost::asio::ip::tcp::acceptor acceptor(ios, endpoint);

for (;;)
{
boost::asio::ip::tcp::iostream stream;
boost::system::error_code ec;
acceptor.accept(*stream.rdbuf(), ec);

if (!ec) {
std::ofstream of;
of.open("rcv.jpg", std::ios::binary);

// read the file content with stream
// write content to file
}
}

最佳答案

我填写了文档示例中缺失的部分:

http://www.boost.org/doc/libs/1_62_0/doc/html/boost_asio/example/cpp03/iostreams/daytime_server.cpp

这是一个简单的发送者/接收者程序,(我认为)它可以满足您的期望:

Live On Coliru

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/copy.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <fstream>
using boost::asio::ip::tcp;

void sender() {
boost::asio::io_service svc;

tcp::iostream sockstream(tcp::resolver::query { "127.0.0.1", "6768" });

boost::iostreams::filtering_ostream out;
out.push(boost::iostreams::zlib_compressor());
out.push(sockstream);

{
std::ifstream ifs("main.cpp", std::ios::binary); // pretend this is your JPEG
out << ifs.rdbuf();
out.flush();
}
}

void receiver() {

int counter = 0;
try
{
boost::asio::io_service io_service;

tcp::endpoint endpoint(tcp::v4(), 6768);
tcp::acceptor acceptor(io_service, endpoint);

for (;;)
{
tcp::iostream stream;
boost::system::error_code ec;
acceptor.accept(*stream.rdbuf(), ec);

{
boost::iostreams::filtering_istream in;
in.push(boost::iostreams::zlib_decompressor());
in.push(stream);

std::ofstream jpg("test" + std::to_string(counter++) + ".out", std::ios::binary);
copy(in, jpg);
}

// break; // just for shorter demo
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
exit(255);
}
}

int main(int argc, char**argv) {
if (--argc && argv[1]==std::string("sender"))
sender();
else
receiver();
}

当您运行接收器时:

./test

并多次使用发件人:

./test sender

接收方将接收到的文件解压并写入test0.out、test1.out等

关于c++ - 使用 boost iostream socket 读写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39923638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com