-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.cpp
75 lines (61 loc) · 1.87 KB
/
client.cpp
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
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>
#include <async/connect.hpp>
#include <async/read_some.hpp>
#include <conduit/coroutine.hpp>
using boost::asio::ip::tcp;
using namespace conduit;
namespace asio = boost::asio;
coroutine read_and_print(tcp::socket socket) {
std::array<char, 1024> buffer;
std::string result;
while (true) {
auto [status, msg] = co_await async::read_some(socket, buffer);
if (status == boost::asio::error::eof) {
break;
}
if (status) {
std::cerr << "Read error: " << status;
break;
}
result += msg;
}
std::cout << result;
}
coroutine connect_and_read(asio::io_context& context, std::string host,
std::string service) {
tcp::resolver resolver(context);
tcp::socket socket(context);
for (auto&& endpoint : resolver.resolve(host, service)) {
auto& status = co_await async::connect(endpoint, socket);
if (status) {
// If the connection to that endpoint failed,
// try the next endpoint
continue;
} else {
// Otherwise, read and print from the now-connected socket
read_and_print(std::move(socket));
co_return;
}
}
// If none of the endpoints connected, print error
std::cerr << "Could not resolve host\n";
}
int main(int argc, char* argv[]) {
try {
if (argc != 2) {
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_context context;
auto run = [&]() { context.run(); };
for (int i = 0; i < 1000; i++)
connect_and_read(context, argv[1], "daytime");
run();
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}