// SPDX-License-Identifier: LGPL-3.0-or-later // Copyright © 2020-2021 Florian Fischer #include <sys/socket.h> #include <sys/types.h> #include <cerrno> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include "Common.hpp" #include "Debug.hpp" #include "Runtime.hpp" #include "io.hpp" const std::string HOST = "::"; const std::string PORT = "12345"; auto main(int argc, char* argv[]) -> int { std::string host = HOST; std::string port = PORT; if (argc > 2) { std::cerr << "Usage: " << argv[0] << " [port]" << std::endl; exit(EXIT_FAILURE); } if (argc > 1) { port = std::string(argv[1]); } std::cout << "Echoserver listening on " << host << ":" << port << std::endl; Runtime runtime; auto* listener = emper::io::tcp_listener(host, port, [](int socket) { // NOLINTNEXTLINE(modernize-avoid-c-arrays) char buf[1024]; for (;;) { ssize_t bytes_recv = emper::io::recvAndWait(socket, buf, sizeof(buf), 0); if (unlikely(bytes_recv <= 0)) { // socket was shutdown if (bytes_recv < 0) { LOGE("server read failed:" << strerror(errno)); } finish: emper::io::closeAndForget(socket); return; } if (unlikely(bytes_recv == 5 && strncmp("quit\n", buf, bytes_recv) == 0)) { exit(EXIT_SUCCESS); } ssize_t bytes_send = emper::io::sendAndWait(socket, buf, bytes_recv, MSG_NOSIGNAL, true); if (unlikely(bytes_recv != bytes_send)) { LOGE("server send failed: " << strerror(errno)); goto finish; } } }); if (!listener) { exit(EXIT_FAILURE); } runtime.scheduleFromAnywhere(*listener); runtime.waitUntilFinished(); return EXIT_FAILURE; }