-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
51 lines (38 loc) · 1.49 KB
/
main.cpp
File metadata and controls
51 lines (38 loc) · 1.49 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
#include <print>
#include <string>
#include "TcpClient.hpp"
using namespace std::literals;
using boost::asio::awaitable;
using boost::asio::deferred;
using boost::asio::detached;
auto send_loop(std::shared_ptr<Channel> to_socket) -> awaitable<void> {
const auto ex = co_await boost::asio::this_coro::executor;
for (int i = 0;; ++i) {
co_await boost::asio::steady_timer{ex, 2s}.async_wait(deferred);
const std::string msg = "msg" + std::to_string(i) + "\n";
co_await to_socket->async_send(boost::system::error_code{}, msg, deferred);
}
}
auto read_loop(std::shared_ptr<Channel> from_socket) -> awaitable<void> {
const auto ex = co_await boost::asio::this_coro::executor;
for (;;) {
auto data = co_await from_socket->async_receive(deferred);
std::print(stdout, "receive: {}", data);
}
}
auto main() -> int try {
const auto host = "127.0.0.1"s;
static constexpr auto port = uint16_t{55555};
boost::asio::io_context io{1};
const auto to_socket = std::make_shared<Channel>(io, 0);
const auto from_socket = std::make_shared<Channel>(io, 0);
const auto client_strand = boost::asio::make_strand(io);
co_spawn(client_strand, start_tcp_client(host, port, to_socket, from_socket), detached);
co_spawn(io, send_loop(to_socket), detached);
co_spawn(io, read_loop(from_socket), detached);
io.run();
} catch (std::exception &e) {
std::println(stderr, "Exception {}", e.what());
} catch (...) {
std::println(stderr, "Unknown exception");
}