该笔记,以官方异步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
|
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) { return pointer(new tcp_connection(io_context)); }
tcp::socket &socket() { return socket_; }
void start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), [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_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) { if(!error) { new_connection->start(); }
start_accept(); }
void start_accept() { tcp_connection::pointer new_connection = tcp_connection::create(io_context_);
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() { 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) { 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;
tcp_server server(io, [](tcp_connection::pointer conn) { 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); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], std::to_string(PORT)); tcp::socket socket(io_context); boost::asio::connect(socket, endpoints);
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抽象类接口
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_;
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_->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: 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>(); tcp_server server(io, handler, 8031); io.run(); return 0; }
|