-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho_server.cpp
More file actions
49 lines (43 loc) · 1.25 KB
/
Copy pathecho_server.cpp
File metadata and controls
49 lines (43 loc) · 1.25 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
#include "rio/buffer.hpp"
#include "rio/io_context.hpp"
#include "rio/net/listener.hpp"
#include "rio/net/protocol.hpp"
#include "rio/net/socket.hpp"
#include "rio/task.hpp"
#include <cstdio>
using namespace rio;
using namespace rio::net;
static Task<void> HandleConnection(IoContext& ctx, Socket<Tcp> conn) {
Buffer buf;
while (true) {
auto n = co_await conn.AsyncRead(buf);
if (!n) {
std::printf("[echo] fd=%d closed\n", conn.Fd());
co_return;
}
while (buf.readableBytes() > 0) {
auto w = co_await conn.AsyncWrite(buf);
if (!w)
co_return;
}
}
}
static Task<void> AcceptLoop(IoContext& ctx, Listener<Tcp>& listener) {
while (true) {
auto result = co_await listener.AsyncAccept();
if (!result)
continue;
std::printf("[echo] accepted fd=%d\n", result->Fd());
Spawn(ctx, HandleConnection(ctx, std::move(*result)));
}
}
// echo server: 监听 8080,原样返回收到的数据
// 测试: echo "hello" | nc localhost 8080
int main() {
auto ctx = std::move(*IoContext::Create());
auto listener = std::move(
*Listener<Tcp>::Create(ctx, Endpoint<Tcp>(AddressV4::Any(), 8080)));
std::printf("[echo] listening on 0.0.0.0:8080\n");
Spawn(ctx, AcceptLoop(ctx, listener));
ctx.Run();
}