我不知道直接映射。但是,如果您有兴趣,编写这样的设备相当简单。此版本会抛出boost::system::system_error
非 EOF 错误,但您可以选择执行其他操作。
#include <iosfwd>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/iostreams/categories.hpp>
#include <boost/system/system_error.hpp>
class asio_stream_device
{
public:
typedef char char_type;
typedef boost::iostreams::bidirectional_device_tag category;
explicit asio_stream_device(boost::asio::ip::tcp::socket& sock) : socket_(sock)
{
}
std::streamsize read(char* s, std::streamsize n)
{
// Read up to n characters from the underlying data source
// into the buffer s, returning the number of characters
// read; return -1 to indicate EOF
boost::system::error_code ec;
std::size_t rval = socket_.read_some(boost::asio::buffer(s, n), ec);
if (!ec)
{
return rval;
}
else if (ec == boost::asio::error::eof)
{
return -1;
}
else
{
throw boost::system::system_error(ec,"read_some");
}
}
std::streamsize write(const char* s, std::streamsize n)
{
// Write up to n characters to the underlying
// data sink into the buffer s, returning the
// number of characters written
boost::system::error_code ec;
std::size_t rval = socket_.write_some(boost::asio::buffer(s, n), ec);
if (!ec)
{
return rval;
}
else if (ec == boost::asio::error::eof)
{
return -1;
}
else
{
throw boost::system::system_error(ec,"write_some");
}
}
private:
boost::asio::ip::tcp::socket& socket_;
};
基本上,正常打开/连接套接字,然后将其传递给构造函数。该示例只是读取并输出到屏幕。
void test
{
namespace asio = boost::asio;
namespace io = boost::iostreams;
asio::io_service service;
asio::ip::tcp::socket socket(service);
asio::ip::tcp::endpoint remote - ...; ////
socket.connect(remote);
io::stream<asio_stream_device> str(socket);
std::string line;
while (std::getline(str, line)) {
std::cout << line << std::endl;
}
}