我的协议很简单:我发送了一个size_t
指示身体大小的信息,然后是身体本身。
代码基于官方的Boost示例,这里是:
class tcp_conn :
public std::enable_shared_from_this<tcp_conn>,
private boost::noncopyable
{
public:
tcp_conn(ba::io_service& io_service);
void start();
void stop();
tcp::socket& socket();
private:
void handle_read_header(const error_code& e, std::size_t bytes_transferred);
void handle_read(const error_code& e, std::size_t bytes_transferred);
ba::streambuf::mutable_buffers_type buffer_wrapper_;
ba::streambuf buffer_;
std::size_t buffer_size_;
tcp::socket socket_;
};
实现是:
void tcp_conn::start() {
socket_.async_read_some(
ba::buffer(&buffer_size_, sizeof(buffer_size_)),
boost::bind(
&tcp_conn::handle_read_header,
this,
ba::placeholders::error,
ba::placeholders::bytes_transferred
)
);
}
void tcp_conn::handle_read_header(const boost::system::error_code& e, std::size_t bytes_transferred){
if(!e) {
buffer_wrapper_ = buffer_.prepare(buffer_size_);
socket_.async_read_some(
ba::buffer(buffer_wrapper_),
boost::bind(
&tcp_conn::handle_read,
this,
ba::placeholders::error,
ba::placeholders::bytes_transferred
)
);
} else {
//stop connection
}
}
void tcp_conn::handle_read(const boost::system::error_code& e, std::size_t bytes_transferred) {
if (!e ) {
buffer_.commit(bytes_transferred);
if(buffer_.size() == buffer_size_) {
std::cout << "WHOLE BODY TRANSFERED NOW" << std::endl;
//has all data in buffer, handle it.
}
else {
std::cout << "NOT WHOLE BODY TRANSFERED, still got "<< (buffer_size_ - bytes_transferred) << " to go" << std::endl;
socket_.async_read_some(
ba::buffer(buffer_wrapper_),
boost::bind(
&tcp_conn::handle_read,
this,
ba::placeholders::error,
ba::placeholders::bytes_transferred
)
);
}
}
else {
//handle error
}
}
这不太行。我猜我的错误是在递归更新中的某个地方buffer_wrapper_
——一些数据丢失了,被覆盖了?