Skip to content

Instantly share code, notes, and snippets.

@mtrencseni
Created April 8, 2023 14:01
Show Gist options
  • Save mtrencseni/3356b8724ad6e40128909a07bbd10d9a to your computer and use it in GitHub Desktop.
Save mtrencseni/3356b8724ad6e40128909a07bbd10d9a to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <asio.hpp>
#include <asio/io_context.hpp>
#include <signal.h>
#include "Utils.hpp"
#include "MessageQueue.hpp"
using asio::awaitable;
using asio::co_spawn;
using asio::detached;
using asio::ip::tcp;
using asio::use_awaitable;
using asio::io_context;
using namespace std;
static MessageQueue mq;
awaitable<void> session(tcp::socket socket)
{
try
{
Dict msg;
string data;
Client client(socket);
cout << "Client connected: " << socket.remote_endpoint() << '\n';
mq.OnConnect(client);
while (data != "quit")
{
data.clear();
co_await asio::async_read_until(socket, asio::dynamic_buffer(data), '\n', use_awaitable); // line-by-line reading
trim(data);
auto lines = split(data, '\n');
for (auto& line : lines)
{
trim(line);
if (line != "") {
cout << "Received: " << line << endl;
mq.OnMessage(client, line);
}
}
}
mq.OnDisconnect(client);
cout << "Client disconnected: " << socket.remote_endpoint() << '\n';
}
catch (const std::exception& e)
{
cout << "Exception in session: " << e.what() << '\n';
}
}
awaitable<void> listener(io_context& ctx, unsigned short port)
{
tcp::acceptor acceptor(ctx, { tcp::v4(), port });
cout << "Server listening on port " << port << "..." << endl;
while (true)
{
tcp::socket socket = co_await acceptor.async_accept(use_awaitable);
co_spawn(ctx, session(move(socket)), detached);
}
}
int main(int argc, char* argv[])
{
if (argc < 2)
{
cerr << "Usage: " << argv[0] << " <port>" << endl;
return 1;
}
io_context ctx;
string arg = argv[1];
size_t pos;
unsigned short port = stoi(arg, &pos);
asio::signal_set signals(ctx, SIGINT, SIGTERM);
signals.async_wait([&](auto, auto) { ctx.stop(); });
auto listen = listener(ctx, port);
co_spawn(ctx, move(listen), asio::detached);
ctx.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment