首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

boost:asio 联接管理9

2013-01-23 
boost::asio 连接管理9这节先重构下代码,业务逻辑代码和通信基础设施代码需要解耦。业务逻辑代码处理通信过

boost::asio 连接管理9

这节先重构下代码,业务逻辑代码和通信基础设施代码需要解耦。业务逻辑代码处理通信过程中的协议,以及背后需要的应用逻辑。而通信基础设施代码专注于并发,TCP连接等特性。

首先把前面的代码Connection的一些成员函数纯虚函数,业务类可以继承之,根据需要重写虚函数。

Server类编程模板类,接受业务类作为模板参数,只要该类提供几个必须的公有成员函数即可。

因此目录结构调整如下:

#include "business/client.h"#include <boost/bind.hpp>using namespace boost;Client::Client(io_service& s):  Connection(s), read_buffer_(1, 0) {}void Client::StartJob() {    async_read(socket, buffer(read_buffer_),       strand_.wrap(bind(&Client::AfterReadChar, shared_from_this(), _1)));}void Client::CloseSocket() {  Connection::CloseSocket();}void Client::AfterReadChar(error_code const& ec) {    if (ec) {        cout << ec.message() << endl;        return;    }        char x = read_buffer_[0];    if (x == 'a') {        cout << "correct data received" << endl;        async_read(socket, buffer(read_buffer_),   strand_.wrap(bind(&Client::AfterReadChar, shared_from_this(), _1)));    } else {        cout << "wrong data received, char is:" << (int) x << endl;        CloseSocket();    }}

好了,现在这个解耦够用了。下一节进行测试。


热点排行