Send and receiving compressed files with boost over socket

血红的双手。 提交于 2021-01-27 13:05:09

问题


In my project, read and write messages over socket are compressed with Zlib Filters of boost, i would like to know how to do the same with files. what better way for better speed? Save the data in buffer without use hard disk?

I'm having trouble to transferring files using boost, so any help and examples are welcome.

I am using the following code to send compressed messages:

std::string data_
std::stringstream compressed;
std::stringstream original;

original << data_;

boost::iostreams::filtering_streambuf<boost::iostreams::input> out;
out.push(boost::iostreams::zlib_compressor());
out.push(original);
boost::iostreams::copy(out, compressed);

data_ = compressed.str();
boost::asio::write(socket_, boost::asio::buffer(data_ + '\n'));

EDIT:

I want to know how to compress a file without having to save a compressed copy in the HD. Saving your bytes directly into a buffer and then send to the socket. Server-side must receive the file and decompress


回答1:


Here's the simplest thing I can think of that does what it appears you're trying to do:

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>

int main() {
    std::string data_ = "hello world\n";
    boost::asio::io_service svc;

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

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

    out << data_;
    out.flush();
}

Use a simple command line listener, e.g.:

netcat -l -p 6767 | zlib-flate -uncompress

Which happily reports "hello world" when it receives the data from the c++ client.



来源:https://stackoverflow.com/questions/39908022/send-and-receiving-compressed-files-with-boost-over-socket

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!