Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions echo_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ using asio::ip::tcp;

const size_t port = 6970;
asio::io_context io;
asio::ip::tcp::acceptor server(io, tcp::endpoint(tcp::v4(), port));
asio::ip::tcp::acceptor server{io, tcp::endpoint{tcp::v4(), port}};

class Request {
public:
Expand All @@ -22,25 +22,30 @@ 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());
const auto &msg = error.message();
printf("Error while accepting: %s\n", msg.c_str());
return;
}

auto request = std::make_shared<Request>(std::move(socket));
auto request = std::make_unique<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) {
auto req = request.get();
asio::async_read_until(req->socket, req->buffer, '\n',
[request = std::move(request)](const auto &error, size_t bytes_transferred) mutable {
if (error) {
printf("Error while reading: %s\n", error.message().c_str());
const auto &msg = error.message();
printf("Error while reading: %s\n", msg.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) {
auto req = request.get();
asio::async_write(req->socket, req->buffer,
[request = std::move(request)](const auto &error, size_t bytes_transferred) mutable {
if (error) {
printf("Error while writing: %s\n", error.message().c_str());
const auto &msg = error.message();
printf("Error while writing: %s\n", msg.c_str());
return;
}
printf("Sent %zu bytes\n", bytes_transferred);
Expand All @@ -51,7 +56,7 @@ void handle_request(const std::error_code& error, tcp::socket socket) {
int main()
{
size_t seconds = 5;
asio::steady_timer t(io, asio::chrono::seconds(seconds));
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");
Expand Down