简体   繁体   中英

Send and receiving compressed files with boost over socket

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

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, eg:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM