-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathecho_server.cpp
More file actions
67 lines (55 loc) · 1.94 KB
/
echo_server.cpp
File metadata and controls
67 lines (55 loc) · 1.94 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
65
66
67
#include <cstdio>
#include <memory>
#include <asio.hpp>
using asio::ip::tcp;
const size_t port = 6970;
asio::io_context io;
asio::ip::tcp::acceptor server(io, tcp::endpoint(tcp::v4(), port));
class Request {
public:
explicit Request(tcp::socket &&socket):
socket(std::move(socket))
{}
tcp::socket socket;
asio::streambuf buffer;
};
void handle_request(const std::error_code& error, tcp::socket socket) {
server.async_accept(io, &handle_request); // The Loop
if (error) {
printf("Error while accepting: %s\n", error.message().c_str());
return;
}
auto request = std::make_shared<Request>(std::move(socket));
printf("Accepted connection\n");
asio::async_read_until(request->socket, request->buffer, '\n',
[request](const auto &error, size_t bytes_transferred) {
if (error) {
printf("Error while reading: %s\n", error.message().c_str());
return;
}
printf("Received %zu bytes\n", bytes_transferred);
asio::async_write(request->socket, request->buffer,
[request](const auto &error, size_t bytes_transferred) {
if (error) {
printf("Error while writing: %s\n", error.message().c_str());
return;
}
printf("Sent %zu bytes\n", bytes_transferred);
});
});
}
int main()
{
size_t seconds = 5;
asio::steady_timer t(io, asio::chrono::seconds(seconds));
printf("Waiting for %zu seconds\n", seconds);
t.async_wait([seconds](const std::error_code &e) {
printf("------------------------------\n");
printf("Done waiting %zu seconds. Error: %s\n", seconds, e.message().c_str());
printf("------------------------------\n");
});
printf("Listening too 127.0.0.1:%zu\n", port);
server.async_accept(io, &handle_request);
io.run();
return 0;
}