-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathecho_server.cpp
More file actions
81 lines (70 loc) · 1.82 KB
/
echo_server.cpp
File metadata and controls
81 lines (70 loc) · 1.82 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <boost/asio.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/asio/co_spawn.hpp>
#include <boost/asio/detached.hpp>
#include <boost/asio/use_awaitable.hpp>
#include <iostream>
#include <memory>
using boost::asio::awaitable;
using boost::asio::co_spawn;
using boost::asio::detached;
using boost::asio::use_awaitable;
using boost::asio::ip::tcp;
/**
* @brief 协程式会话处理
* 使用 co_await 进行异步读写,替代旧版回调式实现。
*/
awaitable<void> handleSession(tcp::socket socket)
{
try
{
char data[1024];
for (;;)
{
// 协程式异步读取
auto bytesRead = co_await socket.async_read_some(boost::asio::buffer(data), use_awaitable);
// 协程式异步写入(Echo 回写)
co_await boost::asio::async_write(socket, boost::asio::buffer(data, bytesRead), use_awaitable);
}
}
catch (const std::exception&)
{
// 连接关闭或错误,会话结束
}
}
/**
* @brief 协程式连接接受器
*/
awaitable<void> listener(tcp::acceptor acceptor)
{
for (;;)
{
// 协程式异步接受连接
auto socket = co_await acceptor.async_accept(use_awaitable);
// 为每个连接启动一个独立的协程
co_spawn(acceptor.get_executor(), handleSession(std::move(socket)), detached);
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "用法: echo_server <端口>\n";
return 1;
}
boost::asio::io_context ioContext;
auto port = static_cast<unsigned short>(std::atoi(argv[1]));
tcp::acceptor acceptor(ioContext, tcp::endpoint(tcp::v4(), port));
// 启动监听协程
co_spawn(ioContext, listener(std::move(acceptor)), detached);
std::cout << "Echo Server(协程式)启动在端口 " << argv[1] << std::endl;
ioContext.run();
}
catch (const std::exception& e)
{
std::cerr << "异常: " << e.what() << std::endl;
}
return 0;
}