|
Boost Users : |
Subject: Re: [Boost-users] How to upload a file with ASIO
From: Ramon F Herrera (ramon_at_[hidden])
Date: 2009-11-03 11:36:50
Benjamin Sobotta wrote:
> Hello,
>
> It would be interesting to know *how* you exactly transfer the
> information at hand and then build a solution from there.
>
> Anyways, I use ASIO in conjunction with boost::serialization. There is
> an example on the ASIO website. I found that combination extremely
> handy. With this approach one could easily transfer any kind of data,
> for example in a std::vector.
>
> hth,
>
> Benjamin
>
>
Hi Benjamin,
Find below the relevant snippets of the client and the server code. As
you can see, I keep on sending parameters, separated by newlines. Two
consecutive newlines denote end of input. This obviously does not scale
to a more complex transfer (i.e., a complete binary file).
Thanks for your kind assistance,
-Ramon
----------------------------------------
Client:
// stream
boost::asio::streambuf buf;
std::ostream net_out(&buf);
// Display the arguments
if (debug()) cout << "client pushing " << argc - 1 << "
arguments" << endl;
for (int i = 1; i < argc; i++) {
net_out << argv[i] << endl;
if (debug()) cout << "arg[" << i << "], " << argv[i] << "
was pushed" << endl;
}
net_out << endl;
boost::asio::write(socket, buf);
while (true) {
boost::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other
error.
cout.write(buf.data(), len);
}
----------------------------------------
Server:
while (true) {
tcp::socket socket(io_service);
acceptor.accept(socket);
///////////////////////////////////////////////////////////////////////////////////
boost::asio::streambuf buf;
boost::system::error_code error;
// read till end-of-args marker
boost::asio::read_until(socket, buf, "\n\n");
// extract args from buf
std::istream net_in(&buf);
while (getline(net_in, next_line)) {
if (next_line.length()) client_argv.push_back(next_line);
}
if (debug()) cout << client_argv.size() << " arguments
received by server" << endl;
///////////////////////////////////////////////////////////////////////////////////
ostringstream response;
it_takes_two_to_tango(client_argv, tx, db, response);
client_argv.clear();
string message = response.str();
// if (debug()) cout << "Deliver to server:" << endl <<
message << endl;
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
}
}
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net