-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscard_server.cpp
More file actions
48 lines (42 loc) · 1.27 KB
/
Copy pathdiscard_server.cpp
File metadata and controls
48 lines (42 loc) · 1.27 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
#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;
size_t total = 0;
while (true) {
auto n = co_await conn.AsyncRead(buf);
if (!n) {
std::printf("[discard] fd=%d closed, total %zu bytes discarded\n",
conn.Fd(), total);
co_return;
}
total += *n;
buf.Reset();
}
}
static Task<void> AcceptLoop(IoContext& ctx, Listener<Tcp>& listener) {
while (true) {
auto result = co_await listener.AsyncAccept();
if (!result)
continue;
std::printf("[discard] accepted fd=%d\n", result->Fd());
Spawn(ctx, HandleConnection(ctx, std::move(*result)));
}
}
// discard server: 监听 9000,接收数据但不回复(丢弃)
// 测试: dd if=/dev/zero bs=1M count=100 | nc localhost 9000
int main() {
auto ctx = std::move(*IoContext::Create());
auto listener = std::move(
*Listener<Tcp>::Create(ctx, Endpoint<Tcp>(AddressV4::Any(), 9000)));
std::printf("[discard] listening on 0.0.0.0:9000\n");
Spawn(ctx, AcceptLoop(ctx, listener));
ctx.Run();
}