socket通信框架——boost asio
boost asio是一个封装了基本socket的跨平台通信框架。它支持异步访问,并支持tcp的自动封闭控制等操作。
一个简单的通信协议可以为:
header | body |
body长 | 数据 |
通过boost::asio接收的话,即可为:
void receive_header() { auto keep_alive(shared_from_this()); auto asbuf = boost::asio::buffer(msg->header(), msg->header_length()); auto on_header_received = [this, keep_alive] (boost::system::error_code ec, std::size_t length) { if (!ec && buffer->decode_header()) { receive_body(); } }; boost::asio::async_read(socket_id, asbuf, on_header_received); } void receive_body() { auto keep_alive(shared_from_this()); auto asbuf = boost::asio::buffer(msg->body(), msg->body_length()); auto on_body_received = [this, keep_alive] (boost::system::error_code ec, std::size_t length) { if (!ecode && msg->body_length()) { // do something } receive_header(); } boost::asio::async_read(socket_id, asbuf, on_body_received); }
而一个简单的发送数据端可为:
void send(Message msg) { boost::system::error_code ec; std::uint32_t posted = 0; std::uint32_t rest = msg.length(); msg.encode_header(); do
{ auto asbuf = boost::asio::buffer(msg.data() + posted, rest); posted = _socket.write_some(asbuf, ec); if (ec) { break; } rest -= posted; } while (rest > 0); }
资料参考: