包装Asio编写异步TCP服务器模型

该笔记,以官方异步TCP服务器实现用例为基础
记录几种改造方向

官方用例

异步 TCP daytime服务器

tcp_connection类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// tcp连接类,继承自 std::enable_shared_from_this<tcp_connection>
// 提供了一个更安全的获取对象自身指针引用的方法
// 将业务逻辑 make_daytime_string 硬编码在该对象中
//
// tcp连接 以及 套接字接口 (运输层 + 套接字)
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
using pointer = std::shared_ptr<tcp_connection>;
private:

tcp::socket socket_;
std::string message_;

private:
tcp_connection(boost::asio::io_context &io_context)
: socket_(io_context)
{ }

void handle_write(const boost::system::error_code &ec, size_t len)
{ }

public:
static pointer create(boost::asio::io_context &io_context)
{
// 通过shared_ptr将该tcp连接对象引出
return pointer(new tcp_connection(io_context));
}

// 引用该tcp连接的套接字对象
tcp::socket &socket()
{
return socket_;
}

// 打开连接,发送字节流
void start()
{
// 返回的响应字节流
message_ = make_daytime_string();
// 异步输出字节流
// 使用该tcp连接的套接字
// 传输的字节流
boost::asio::async_write(socket_, boost::asio::buffer(message_),
// 获取指向自身的shared_ptr指针引用
// 包装 handle_write() 方法,对字节流输出进行处理
[self = shared_from_this()]
(const boost::system::error_code &error, std::size_t bytes_transferred) {
self->handle_write(error, bytes_transferred);
}
);
}
};

tcp_server类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 服务器主机(服务器进程)(应用层处理)
class tcp_server
{
public:
tcp_server(boost::asio::io_context &io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 8013))
{
// 打开服务器 start server
start_accept();
}

private:
boost::asio::io_context &io_context_;
tcp::acceptor acceptor_;

// 接受完成事件
void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code &error)
{
// 无错误,则建立一个新tcp连接
if(!error)
{
// 打开一个tcp连接
new_connection->start();
}

// 发起一次异步接收操作,等待客户端连接
start_accept();
}

// 发起一次异步接收操作,等待客户端连接
void start_accept()
{
// 建立新连接 发送数据
tcp_connection::pointer new_connection = tcp_connection::create(io_context_);

// 处理接受连接,(handle_accept中的start发送数据,至指定tcp连接占用的套接字接口)
acceptor_.async_accept(new_connection->socket(),
[this, new_connection]
(const boost::system::error_code &error) {
this->handle_accept(new_connection, error);
}
);
}
};

使用方法

1
2
3
boost::asio::io_context io_context;
tcp_server server(io_context);
io_context.run();

官方用例的问题

该服务器实现,将 TCP连接逻辑 与 业务处理逻辑 耦合在一个 *tcp_connection类 中。仅能作为一个简单的库使用用例。

  • 连接与业务强耦合
  • 难以复用代码进行功能扩充

改造方法

对于以上的问题,有以下 两种简洁的改进方法

是将连接与业务分离的两种方式

回调函数

使用回调lambda函数的方式解决业务写死在tcp_connection类中的问题

改造tcp_connection

  • 添加 handler_type = std::function<void(tcp_connection&)> 类型,承载函数回调
  • 保存一个函数对象 handler_type handler_
  • 在连接打开后直接调用 保存的函数对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
using pointer = std::shared_ptr<tcp_connection>;
using handler_type = std::function<void(pointer)>;
private:
tcp::socket socket_;
handler_type handler_;

private:
tcp_connection(boost::asio::io_context &io_context_, handler_type handler)
: socket_(io_context_),
handler_(std::move(handler))
{}

public:
static pointer create(boost::asio::io_context &io_context_, handler_type handler)
{
return pointer(new tcp_connection(io_context_, std::move(handler)));
}

tcp::socket &socket()
{
return socket_;
}

void start()
{
// 传入指向该对象的shared_ptr
handler_(shared_from_this());
}
};

改造tcp_server

  • 同样的,保存一个 回调函数对象 handler_type handler_
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class tcp_server
{
public:
using handler_type = std::function<void(tcp_connection::pointer)>;

private:
boost::asio::io_context &io_context_;
tcp::acceptor acceptor_;
handler_type handler_;

public:
tcp_server(boost::asio::io_context &io_context, handler_type handler, const int PORT, tcp transport_proto = tcp::v4())
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(transport_proto, PORT)),
handler_(std::move(handler))
{
start_accept();
}

private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(io_context_, handler_);

// 异步接受请求
acceptor_.async_accept(new_connection->socket(),
[this, new_connection]
(const boost::system::error_code &error) {
this->handle_accept(new_connection, error);
}
);
}

void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code &error)
{
if(!error)
{
// 调起业务方法
new_connection->start();
}
// 处理连接后,继续接受请求
start_accept();
}
};

使用方法

  • 需要一串客户的字节流请求,激活异步回调
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
void echo_handler(TCPServer::tcp_connection::pointer conn)
{
auto buffer = std::make_shared<std::string>();
// 异步读取一行
boost::asio::async_read_until(conn->socket(), boost::asio::dynamic_buffer(*buffer), "\n",
[conn, buffer]
(const boost::system::error_code &ec, size_t) {
if (!ec) {
// 异步写回读取到的内容
boost::asio::async_write(conn->socket(), boost::asio::buffer(*buffer),
[conn]
(const boost::system::error_code &ec, size_t) {
// 无论成功或失败,关闭连接(客户端将收到 EOF)
conn->socket().close();
if (ec) {
std::cerr << "Write error: " << ec.message() << std::endl;
} else {
std::cout << "Echoed and closed connection" << std::endl;
}
});
} else {
// 读取失败,关闭连接
conn->socket().close();
std::cerr << "Read error: " << ec.message() << std::endl;
}
});
}

int main(int argc, char *argv[])
{
try {
boost::asio::io_context io;

// 使用 lambda 包装业务逻辑,也可以直接传入 echo_handler
tcp_server server(io,
[](tcp_connection::pointer conn) {
// 调用独立的业务处理函数 echo_handler
echo_handler(conn);
},
8031);

std::cout << "Server started on port 8031" << std::endl;
io.run();
} catch (std::exception &e) {
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
}

适配的client代码

  • 发往服务器一段字节流
  • 回显服务器应答
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace asio = boost::asio;
const int PORT = 8031;

int main(int argc, char *argv[])
{
using boost::asio::ip::tcp;
try
{
if(argc != 2) {
std::cerr << "Usage: client <host.ip>" << std::endl;
return 1;
}

boost::asio::io_context io_context;
tcp::resolver resolver(io_context);
// 连接服务器 ip:port
tcp::resolver::results_type endpoints =
resolver.resolve(argv[1], std::to_string(PORT));
tcp::socket socket(io_context);
// 建立tcp连接
boost::asio::connect(socket, endpoints);

// 先向服务端发送一行数据(必须包含换行符)asyc_read_until
std::string message = "Hello from client\n";
boost::asio::write(socket, boost::asio::buffer(message));
std::cout << "Sent: " << message;

// 读取服务端的回显
while(true)
{
std::array<char, 128> buf;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);

if(error == boost::asio::error::eof)
break; // 读至文件结尾
else if(error)
throw boost::system::system_error(error);

if(len > 0)
std::cout.write(buf.data(), len);
}
std::cout << "\nConnection closed by server." << std::endl;
}
catch(std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}

继承接口类

定义一个名为 request_handler 的抽象类接口

request_handler抽象类接口

  • 其中handle纯虚函数接口的读写逻辑由子类实现
1
2
3
4
5
6
7
class request_handler {
public:
virtual ~request_handler() = default;

// 处理一个连接,具体读写逻辑由子类实现
virtual void handle(tcp_connection::pointer conn) = 0;
};

改造tcp_connection类

  • 使用 shared_ptr 持有指向 request_handler 对象的指针(唯一需要更改之处)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
using pointer = std::shared_ptr<tcp_connection>;

private:
tcp::socket socket_;
std::shared_ptr<request_handler> handler_; // 用 shared_ptr 管理,保证生命周期

tcp_connection(boost::asio::io_context& io_context,
std::shared_ptr<request_handler> handler)
: socket_(io_context), handler_(std::move(handler))
{}

public:
static pointer create(boost::asio::io_context& io_context,
std::shared_ptr<request_handler> handler)
{
return pointer(new tcp_connection(io_context, std::move(handler)));
}

tcp::socket& socket() { return socket_; }

void start()
{
// 调用抽象接口,具体处理逻辑由 handler_ 决定
handler_->handle(shared_from_this());
}
};

改造tcp_server类

  • 几乎无需更改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class tcp_server
{
private:
boost::asio::io_context& io_context_;
tcp::acceptor acceptor_;
std::shared_ptr<request_handler> handler_;

public:
tcp_server(boost::asio::io_context& io_context,
std::shared_ptr<request_handler> handler,
int port, tcp protocol = tcp::v4())
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(protocol, port)),
handler_(std::move(handler))
{
start_accept();
}

private:
void start_accept()
{
auto new_connection =
tcp_connection::create(io_context_, handler_);

acceptor_.async_accept(new_connection->socket(),
[this, new_connection]
(const boost::system::error_code& ec) {
handle_accept(new_connection, ec);
}
);
}

void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& ec)
{
if (!ec) {
// 打开连接
new_connection->start();
}
start_accept();
}

};

实际业务编写

  • 业务类继承抽象接口 request_handler
  • 业务类重写 handle 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class echo_handler
: public request_handler
{
public:
// 重写handle方法
void handle(tcp_connection& conn) override {
auto buffer = std::make_shared<std::string>();
auto& socket = conn.socket();
boost::asio::async_read_until(socket, boost::asio::dynamic_buffer(*buffer), "\n",
[&conn, buffer]
(const boost::system::error_code& ec, size_t) {
if (!ec) {
boost::asio::async_write(conn.socket(), boost::asio::buffer(*buffer),
[self = conn.shared_from_this()]
(auto, auto) {});
}
});
}
};

// 业务编写
class hello_handler
: public request_handler
{
public:
void handle(tcp_connection& conn) override {
boost::asio::async_write(conn.socket(), boost::asio::buffer("Hello World\n"),
[self = conn.shared_from_this()]
(auto, auto) {});
}
};

使用示例

1
2
3
4
5
6
7
int main() {
boost::asio::io_context io;
auto handler = std::make_shared<hello_handler>(); // 或 echo_handler()
tcp_server server(io, handler, 8031);
io.run();
return 0;
}