读书人

Boost asio 确定 接收数据 大小的有

发布时间: 2012-09-07 10:38:15 作者: rapoo

Boost asio 确定 接收数据 大小的问题
类中
connection_.async_read(stocks_,
boost::bind(&client::handle_read, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
类中:
template <typename T, typename Handler>
void async_read(T& t, Handler handler)
{
// Issue a read operation to read exactly the number of bytes in a header.
void (connection::*f)(
const boost::system::error_code&,
T&, boost::tuple<Handler>)
= &connection::handle_read_header<T, Handler>;
boost::asio::async_read(socket_, boost::asio::buffer(inbound_header_),
boost::bind(f,
this, boost::asio::placeholders::error, boost::ref(t),
boost::make_tuple(handler)));
}
template <typename T, typename Handler>
void handle_read_header(const boost::system::error_code& e,
T& t, boost::tuple<Handler> handler)
{
if (e)
{
boost::get<0>(handler)(e);
}
else
{
// Determine the length of the serialized data.
std::istringstream is(std::string(inbound_header_, header_length));
std::size_t inbound_data_size = 0;
if (!(is >> std::hex >> inbound_data_size))
{
// Header doesn't seem to be valid. Inform the caller.
boost::system::error_code error(boost::asio::error::invalid_argument);
boost::get<0>(handler)(error);
return;
}

// Start an asynchronous call to receive the data.
inbound_data_.resize(inbound_data_size);
void (connection::*f)(
const boost::system::error_code&,
T&, boost::tuple<Handler>)
= &connection::handle_read_data<T, Handler>;
boost::asio::async_read(socket_, boost::asio::buffer(inbound_data_),
boost::bind(f, this,
boost::asio::placeholders::error, boost::ref(t), handler));
}
}

/// Handle a completed read of message data.
template <typename T, typename Handler>
void handle_read_data(const boost::system::error_code& e,
T& t, boost::tuple<Handler> handler)
{
if (e)
{
boost::get<0>(handler)(e);
}
else
{
// Extract the data structure from the data just received.
try
{
std::string archive_data(&inbound_data_[0], inbound_data_.size());
std::istringstream archive_stream(archive_data);
boost::archive::text_iarchive archive(archive_stream);
archive >> t;
}
catch (std::exception& e)
{
// Unable to decode data.
boost::system::error_code error(boost::asio::error::invalid_argument);
boost::get<0>(handler)(error);
return;
}

// Inform caller that data has been received ok.
boost::get<0>(handler)(e);
}
}

回调函数中:
void handle_read(const boost::system::error_code& e, size_t bytes_transferred)
{
if (!e)
{
std::cout << "bytes_transferred number " << bytes_transferred << "\n";

为什么会报错!??!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
错误为:不能将参数 3 从“const boost::system::error_code”转换为“size_t”
1> with
1> [
1> R=void,
1> T=s11n_example::client,
1> A1=const boost::system::error_code &,
1> A2=size_t,
1> U=s11n_example::client *
1> ]
1> 没有可用于执行该转换的用户定义的转换运算符,或者无法调用该运算符

[解决办法]
参数传错了

读书人网 >C++

热点推荐