-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.cpp
executable file
·78 lines (69 loc) · 2.24 KB
/
test.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
76
77
78
#include "include/dns_resolver.h"
#include <chrono>
#define THREAD_NUM 3
std::shared_ptr<asio::io_context> context;
std::shared_ptr<dns::resolver<asio::io_context>> resolver;
std::vector<std::thread> threads;
void nothing(const dns::result& err, const std::string& domain, const std::vector<std::string>& res)
{
}
void print_one_line(const dns::result& err, const std::string& domain, const std::vector<std::string>& res)
{
std::cout << "\n";
}
void print(dns::result& err, const std::string& domain, const std::vector<std::string>& res)
{
if (err.is_ok()) {
std::cout << "domain: " << domain << std::endl;
for (const auto& ip : res) {
std::cout << "ip: " << ip << std::endl;
}
} else {
std::cout << err.message() << std::endl;
}
}
void handle_close()
{
std::cout << "The program will quit." << std::endl;
if (context) {
context->stop();
}
for (auto& thread : threads) {
thread.join();
}
resolver.reset();
context.reset();
exit(0);
}
int main(int argc, char const* argv[])
{
try {
signal(SIGINT, [](int sig) {
handle_close();
});
auto servers = dns::get_sys_default_servers();
if (servers.empty()) {
throw std::runtime_error { "there is no dns server of the system." };
}
std::cout << "choose server: " << servers[0] << std::endl;
context.reset(new asio::io_context(THREAD_NUM));
resolver.reset(new dns::resolver<asio::io_context>(context, servers[0],
context, std::chrono::milliseconds {100}, 2)); //use the asio::io_context as the thread pool to execuate callbacks
for (auto i = 0; i != THREAD_NUM; i++) {
threads.emplace_back([]() {
context->run();
});
}
for (auto i = 0; i != 3000; i++) {
resolver->resolve_domain("www.baidu.com", nothing);
resolver->resolve_domain("www.sina.com", nothing);
resolver->resolve_domain("www.google.com", nothing);
}
std::this_thread::sleep_for(std::chrono::seconds { 1 });
handle_close();
} catch (const std::exception& e) {
std::cerr << e.what() << '\n';
handle_close();
}
return 0;
}