-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
76 lines (66 loc) · 2.08 KB
/
Copy pathmain.cpp
File metadata and controls
76 lines (66 loc) · 2.08 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
#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 read_result = co_await conn.AsyncRead(buf);
if (!read_result.has_value()) {
std::printf("[echo] connection closed (read: %s)\n",
read_result.error().ToString().c_str());
co_return;
}
if (*read_result == 0) {
continue;
}
// Write all buffered data back.
while (buf.readableBytes() > 0) {
auto write_result = co_await conn.AsyncWrite(buf);
if (!write_result.has_value()) {
std::printf("[echo] connection closed (write: %s)\n",
write_result.error().ToString().c_str());
co_return;
}
}
}
}
static Task<void> AcceptLoop(IoContext& ctx, Listener<Tcp>& listener) {
while (true) {
auto result = co_await listener.AsyncAccept();
if (!result.has_value()) {
std::printf("[echo] accept error: %s\n",
result.error().ToString().c_str());
continue;
}
auto conn = std::move(*result);
std::printf("[echo] new connection (fd=%d)\n", conn.Fd());
Spawn(ctx, HandleConnection(ctx, std::move(conn)));
}
}
int main() {
auto ctx_result = IoContext::Create();
if (!ctx_result.has_value()) {
std::fprintf(stderr, "IoContext::Create failed: %s\n",
ctx_result.error().ToString().c_str());
return 1;
}
auto ctx = std::move(*ctx_result);
auto ep = Endpoint<Tcp>(AddressV4::Any(), 8080);
auto listener_result = Listener<Tcp>::Create(ctx, ep);
if (!listener_result.has_value()) {
std::fprintf(stderr, "Listener::Create failed: %s\n",
listener_result.error().ToString().c_str());
return 1;
}
auto listener = std::move(*listener_result);
std::printf("[echo] listening on 0.0.0.0:8080\n");
Spawn(ctx, AcceptLoop(ctx, listener));
ctx.Run();
return 0;
}