forked from jbaldwin/libcoro
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoro_http_200_ok_server.cpp
More file actions
64 lines (53 loc) · 1.88 KB
/
coro_http_200_ok_server.cpp
File metadata and controls
64 lines (53 loc) · 1.88 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
#include <coro/coro.hpp>
auto main() -> int
{
auto make_http_200_ok_server = [](std::unique_ptr<coro::scheduler>& scheduler) -> coro::task<void>
{
auto make_on_connection_task = [](coro::net::tcp::client client) -> coro::task<void>
{
std::string response = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n";
std::string buf(1024, '\0');
while (true)
{
auto [rstatus, rspan] = co_await client.read_some(buf);
if (rstatus.is_ok())
{
co_await client.write_some(response);
}
else
{
co_return;
}
}
};
coro::net::tcp::server server{scheduler, {"127.0.0.1", 8888}};
while (true)
{
auto client = co_await server.accept();
if (client)
{
scheduler->spawn_detached(make_on_connection_task(std::move(*client)));
}
else
{
std::cerr << client.error().message();
co_return;
}
}
co_return;
};
std::vector<std::unique_ptr<coro::scheduler>> schedulers{};
std::vector<coro::task<void>> workers{};
const std::size_t count = std::thread::hardware_concurrency();
schedulers.reserve(count);
workers.reserve(count);
for (size_t i = 0; i < count; ++i)
{
auto& scheduler = schedulers.emplace_back(
coro::scheduler::make_unique(
coro::scheduler::options{
.execution_strategy = coro::scheduler::execution_strategy_t::process_tasks_inline}));
workers.emplace_back(scheduler->schedule(make_http_200_ok_server(scheduler)));
}
coro::sync_wait(coro::when_all(std::move(workers)));
}