Basic Network Programming Applications
Socket
A socket is an abstraction mechanism used for communication in networks.
In C++, the socket function is typically used to create a socket.
Creating a Socket
#include <sys/socket.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
return 0;
}
TCP/IP
- TCP/IP is one of the most commonly used protocol suites in the Internet.
- TCP provides reliable, connection-oriented service; IP is responsible for packet routing.
Binding an Address
#include <arpa/inet.h>
#include <netinet/in.h>
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
Listening for Connections
if (listen(sockfd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
Accepting Connections
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (new_sockfd < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
Sending and Receiving Data
char buffer[1024] = {0};
ssize_t bytes_received = recv(new_sockfd, buffer, 1024, 0);
if (bytes_received < 0) {
perror("recv failed");
exit(EXIT_FAILURE);
}
send(new_sockfd, "Hello, Client!", strlen("Hello, Client!"), 0);
UDP
UDP is a connectionless protocol that does not guarantee reliable data transmission.
Multithreading
Multithreading can be used to handle multiple client connections.
Using std::thread makes it easy to create threads in C++.
Non-blocking I/O
Non-blocking I/O can significantly improve program responsiveness.
It is achieved by setting the socket to non-blocking mode.
Complete Application Example
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <vector>
void handle_client(int client_sock) {
char buffer[1024] = {0};
ssize_t bytes_received = recv(client_sock, buffer, 1024, 0);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << std::endl;
send(client_sock, "Hello, Client!", strlen("Hello, Client!"), 0);
}
close(client_sock);
}
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(sockfd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
std::vector<std::thread> threads;
while (true) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (new_sockfd < 0) {
perror("accept failed");
continue;
}
threads.emplace_back(handle_client, new_sockfd);
}
for (auto &t : threads) {
t.join();
}
close(sockfd);
return 0;
}
This server example program listens on port 8080 and creates a new thread to handle each new client connection request.
Non-blocking I/O
Non-blocking I/O can significantly improve the performance of network applications, especially when handling a large number of concurrent connections.
Example Code
#include <fcntl.h>
// Set socket to non-blocking mode
int flags = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
Signal-driven I/O (SIGIO)
Signal-driven I/O allows applications to handle I/O events via signal notifications.
Example Code
#include <signal.h>
void signal_handler(int signum) {
// Handle signal
printf("Signal received: %d\n", signum);
}
int main() {
signal(SIGIO, signal_handler); // Register signal handler
// Other code...
}
Event-driven I/O (epoll)
Event-driven I/O (such as epoll) is a highly efficient I/O multiplexing technique, ideal for handling a large number of concurrent connections.
Example Code
#include <sys/epoll.h>
int main() {
int epoll_fd = epoll_create1(0);
if (epoll_fd == -1) {
perror("epoll_create1 failed");
exit(EXIT_FAILURE);
}
struct epoll_event ev;
ev.events = EPOLLIN; // Listen for read events
ev.data.fd = sockfd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
perror("epoll_ctl failed");
exit(EXIT_FAILURE);
}
struct epoll_event events[10];
int num_events;
while ((num_events = epoll_wait(epoll_fd, events, 10, -1)) > 0) {
for (int i = 0; i < num_events; i++) {
if (events[i].events & EPOLLIN) {
// Read data
char buffer[1024];
ssize_t bytes_received = recv(events[i].data.fd, buffer, 1024, 0);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << std::endl;
}
}
}
}
close(epoll_fd);
return 0;
}
Multithreading and Thread Pool
Multithreading can be used to handle multiple client connections, while a thread pool can efficiently manage these threads.
Example Code
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t num_threads)
: stop(false) {
for (size_t i = 0; i < num_threads; ++i) {
workers.emplace_back(std::bind(&ThreadPool::worker_thread, this));
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) {
worker.join();
}
}
template <class F, class... Args>
auto enqueue(F &&f, Args &&...args) -> std::future<decltype(f(args...))> {
using return_type = decltype(f(args...));
auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
// don't allow enqueueing after stopping the pool
if (stop) {
throw std::runtime_error("enqueue on stopped ThreadPool");
}
tasks.emplace([task]() { (*task)(); });
}
condition.notify_one();
return res;
}
private:
void worker_thread() {
for (;;) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queue_mutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
task();
}
}
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop;
};
int main() {
ThreadPool pool(4); // Create a thread pool with 4 threads
// Assume we have a function to handle client connections
void handle_client(int client_sock) {
char buffer[1024] = {0};
ssize_t bytes_received = recv(client_sock, buffer, 1024, 0);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << std::endl;
send(client_sock, "Hello, Client!", strlen("Hello, Client!"), 0);
}
close(client_sock);
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// ...other initialization code...
while (true) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (new_sockfd < 0) {
perror("accept failed");
continue;
}
pool.enqueue(handle_client, new_sockfd);
}
return 0;
}
SSL/TLS Encrypted Communication
SSL/TLS can be used to encrypt network communication and protect data security.
Example Code
#include <openssl/ssl.h>
#include <openssl/err.h>
int main() {
SSL_library_init();
SSL_load_error_strings();
SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
if (!ctx) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// ...other initialization code...
SSL *ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd);
if (SSL_accept(ssl) <= 0) {
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
// Read encrypted data
char buffer[1024];
ssize_t bytes_received = SSL_read(ssl, buffer, 1024);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << std::endl;
}
// Send encrypted data
SSL_write(ssl, "Hello, Client!", strlen("Hello, Client!"));
SSL_free(ssl);
SSL_CTX_free(ctx);
return 0;
}
HTTP Server
Building a simple HTTP server helps you better understand the basic principles of web development.
Example Code
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void handle_http_request(int client_sock) {
char buffer[1024] = {0};
ssize_t bytes_received = recv(client_sock, buffer, 1024, 0);
if (bytes_received > 0) {
std::cout << "Received: " << buffer << std::endl;
const char *response = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 12\r\n"
"\r\n"
"<h1>Hello!</h1>";
send(client_sock, response, strlen(response), 0);
}
close(client_sock);
}
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8080);
inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(sockfd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
while (true) {
struct sockaddr_in client_addr;
socklen_t client_len = sizeof(client_addr);
int new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_len);
if (new_sockfd < 0) {
perror("accept failed");
continue;
}
handle_http_request(new_sockfd);
}
close(sockfd);
return 0;
}
Asynchronous I/O (Asio Library)
Boost.Asio is a very powerful C++ library for writing high-performance network and low-level I/O programs. It supports both synchronous and asynchronous operations, offering rich functionality and good cross-platform compatibility.
Example Code
#include <boost/asio.hpp>
#include <iostream>
using boost::asio::ip::tcp;
int main() {
try {
boost::asio::io_context io_context;
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 8080));
for (;;) {
tcp::socket socket(io_context);
acceptor.accept(socket);
std::string message = "Hello, Asio!";
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
}
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
HTTP/2 and WebSocket
HTTP/2 is a new version of the HTTP protocol that provides better performance. WebSocket allows establishing a persistent bidirectional communication channel between client and server.
Example Code (using Boost.Beast)
#include <boost/beast.hpp>
#include <boost/asio.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/strand.hpp>
#include <cstdlib>
#include <functional>
#include <memory>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class session : public std::enable_shared_from_this<session> {
public:
session(net::io_context& ioc, tcp::socket&& socket)
: resolver_(ioc),
ws_(std::move(socket)),
strand_(ioc) {}
void run() {
beast::get_lowest_layer(ws_).expires_never();
ws_.set_option(websocket::stream_base::timeout::suggested(beast::role_type::server));
ws_.set_option(websocket::stream_base::decorator([](websocket::request_type& req) {
req.set(http::field::server, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-server-async");
}));
ws_.async_accept(strand_.wrap(std::bind(&session::on_accept, shared_from_this(),
std::placeholders::_1)));
}
private:
void on_accept(beast::error_code ec) {
if (ec) {
return fail(ec, "accept");
}
do_read();
}
void do_read() {
ws_.async_read(buffer_,
strand_.wrap(std::bind(&session::on_read, shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void on_read(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "read");
}
// Echo the message
ws_.async_write(buffer_.data(),
strand_.wrap(std::bind(&session::on_write, shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
// Clear the buffer
buffer_.consume(buffer_.size());
}
void on_write(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "write");
}
// Read another message
do_read();
}
void fail(beast::error_code ec, char const* what) {
std::cerr << what << ": " << ec.message() << "\n";
return;
}
tcp::resolver resolver_;
websocket::stream<tcp::socket> ws_;
beast::flat_buffer buffer_;
net::strand<net::io_context::executor_type> strand_;
};
int main(int argc, char* argv[]) {
try {
namespace ip = boost::asio::ip;
boost::asio::io_context ioc;
ip::tcp::acceptor acceptor(ioc, {ip::tcp::v4(), 8080});
for (;;) {
ip::tcp::socket socket(ioc);
acceptor.accept(socket);
std::make_shared<session>(ioc, std::move(socket))->run();
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return EXIT_SUCCESS;
}
Load Balancing
Load balancing refers to distributing network traffic across multiple servers to improve system availability and response speed.
Example Code (using NGINX or HAProxy) Load balancing is typically not implemented directly in the application but through external tools like NGINX or HAProxy. Here is a simple NGINX configuration example:
http {
upstream backend {
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend;
}
}
}
Microservices Architecture
Microservices architecture is a design pattern in which an application is broken down into a set of small, independent services, each running in its own process and communicating via lightweight mechanisms (usually HTTP-based APIs).
Example Code (using RESTful API)
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <cstdlib>
#include <functional>
#include <memory>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class rest_service : public std::enable_shared_from_this<rest_service> {
public:
rest_service(net::io_context& ioc, tcp::socket&& socket)
: resolver_(ioc),
http_stream_(std::move(socket)),
strand_(ioc) {}
void run() {
http_stream_.expires_never();
http_stream_.set_option(
net::socket_base::reuse_address(true));
http_stream_.async_read(
buffer_,
http::dynamic_body,
strand_.wrap(std::bind(&rest_service::on_read, shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
private:
void on_read(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "read");
}
// Handle the request
http::response<http::string_body> res{http::status::ok, http_stream_.get_executor()};
res.set(http::field::server, "REST Service");
res.set(http::field::content_type, "text/plain");
res.keep_alive(http_stream_.is_keep_alive());
res.body() = "Hello, REST!";
res.prepare_payload();
// Send the response
http_stream_.async_write(
res,
strand_.wrap(std::bind(&rest_service::on_write, shared_from_this(),
std::placeholders::_1)));
}
void on_write(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "write");
}
// Gracefully close the stream
http_stream_.async_close(
beast::bind_front_handler(
&rest_service::on_close,
shared_from_this()));
}
void on_close(beast::error_code ec) {
if (ec) {
return fail(ec, "close");
}
}
void fail(beast::error_code ec, char const* what) {
std::cerr << what << ": " << ec.message() << "\n";
}
tcp::resolver resolver_;
beast::tcp_stream http_stream_;
beast::flat_buffer buffer_;
net::strand<net::io_context::executor_type> strand_;
};
int main(int argc, char* argv[]) {
try {
namespace ip = boost::asio::ip;
boost::asio::io_context ioc;
ip::tcp::acceptor acceptor(ioc, {ip::tcp::v4(), 8080});
for (;;) {
ip::tcp::socket socket(ioc);
acceptor.accept(socket);
std::make_shared<rest_service>(ioc, std::move(socket))->run();
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return EXIT_SUCCESS;
}
In this example, we created a simple RESTful service that receives requests and returns a simple text response. This service can be part of a larger microservices architecture.
Security
Security is crucial for any network application. Here are some common security measures:
- HTTPS: Use SSL/TLS encryption to protect data transmission.
- Authentication and Authorization: Ensure only authorized users can access specific resources.
- Input Validation: Prevent SQL injection and other forms of data injection attacks.
- CORS: Control cross-origin resource sharing to prevent malicious websites from accessing your service.
Example Code (using HTTPS)
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl.hpp>
#include <cstdlib>
#include <functional>
#include <memory>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class https_service : public std::enable_shared_from_this<https_service> {
public:
https_service(net::io_context& ioc, ssl::context& ctx, tcp::socket&& socket)
: resolver_(ioc),
http_stream_(std::move(socket), ctx),
strand_(ioc) {}
void run() {
http_stream_.expires_never();
http_stream_.set_option(
net::socket_base::reuse_address(true));
http_stream_.async_handshake(ssl::stream_base::server,
strand_.wrap(std::bind(&https_service::on_handshake, shared_from_this(),
std::placeholders::_1)));
}
private:
void on_handshake(beast::error_code ec) {
if (ec) {
return fail(ec, "handshake");
}
http_stream_.async_read(
buffer_,
http::dynamic_body,
strand_.wrap(std::bind(&https_service::on_read, shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
void on_read(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "read");
}
// Handle the request
http::response<http::string_body> res{http::status::ok, http_stream_.get_executor()};
res.set(http::field::server, "HTTPS Service");
res.set(http::field::content_type, "text/plain");
res.keep_alive(http_stream_.is_keep_alive());
res.body() = "Hello, HTTPS!";
res.prepare_payload();
// Send the response
http_stream_.async_write(
res,
strand_.wrap(std::bind(&https_service::on_write, shared_from_this(),
std::placeholders::_1)));
}
void on_write(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "write");
}
// Gracefully close the stream
http_stream_.async_shutdown(
beast::bind_front_handler(
&https_service::on_shutdown,
shared_from_this()));
}
void on_shutdown(beast::error_code ec) {
if (ec) {
return fail(ec, "shutdown");
}
}
void fail(beast::error_code ec, char const* what) {
std::cerr << what << ": " << ec.message() << "\n";
}
tcp::resolver resolver_;
beast::ssl_stream<beast::tcp_stream> http_stream_;
beast::flat_buffer buffer_;
net::strand<net::io_context::executor_type> strand_;
};
int main(int argc, char* argv[]) {
try {
namespace ip = boost::asio::ip;
boost::asio::io_context ioc;
ssl::context ctx{ssl::context::tlsv12};
// Load certificates and keys
ctx.use_certificate_chain_file("server.crt");
ctx.use_private_key_file("server.key", ssl::context::pem);
ctx.set_verify_mode(ssl::verify_none);
ip::tcp::acceptor acceptor(ioc, {ip::tcp::v4(), 443});
for (;;) {
ip::tcp::socket socket(ioc);
acceptor.accept(socket);
std::make_shared<https_service>(ioc, ctx, std::move(socket))->run();
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
return EXIT_SUCCESS;
}
Logging and Monitoring
Logging and monitoring are key factors in maintaining system stability and performance. They help developers track errors, debug issues, and optimize performance.
Example Code (using spdlog library)
#include <spdlog/spdlog.h>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/beast/http.hpp>
#include <cstdlib>
#include <functional>
#include <memory>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class logging_service : public std::enable_shared_from_this<logging_service> {
public:
logging_service(net::io_context& ioc, tcp::socket&& socket)
: resolver_(ioc),
http_stream_(std::move(socket)),
strand_(ioc) {}
void run() {
http_stream_.expires_never();
http_stream_.set_option(
net::socket_base::reuse_address(true));
http_stream_.async_read(
buffer_,
http::dynamic_body,
strand_.wrap(std::bind(&logging_service::on_read, shared_from_this(),
std::placeholders::_1,
std::placeholders::_2)));
}
private:
void on_read(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "read");
}
// Log the request
spdlog::info("Received request: {}", beast::buffers_to_string(buffer_.data()));
// Handle the request
http::response<http::string_body> res{http::status::ok, http_stream_.get_executor()};
res.set(http::field::server, "Logging Service");
res.set(http::field::content_type, "text/plain");
res.keep_alive(http_stream_.is_keep_alive());
res.body() = "Hello, Logging!";
res.prepare_payload();
// Send the response
http_stream_.async_write(
res,
strand_.wrap(std::bind(&logging_service::on_write, shared_from_this(),
std::placeholders::_1)));
}
void on_write(beast::error_code ec, std::size_t bytes_transferred) {
boost::ignore_unused(bytes_transferred);
if (ec) {
return fail(ec, "write");
}
// Log the response
spdlog::info("Sent response: {}", res.body());
// Gracefully close the stream
http_stream_.async_close(
beast::bind_front_handler(
&logging_service::on_close,
shared_from_this()));
}
void on_close(beast::error_code ec) {
if (ec) {
return fail(ec, "close");
}
}
void fail(beast::error_code ec, char const* what) {
std::cerr << what << ": " << ec.message() << "\n";
}
tcp::resolver resolver_;
beast::tcp_stream http_stream_;
beast::flat_buffer buffer_;
net::strand<net::io_context::executor_type> strand_;
};
int main(int argc, char* argv[]) {
try {
namespace ip = boost::asio::ip;
boost::asio::io_context ioc;
// Initialize logger
auto console_logger = spdlog::stdout_color_mt("console");
console_logger->set_level(spdlog::level::info);
ip::tcp::acceptor acceptor(ioc, {ip::tcp::v4(), 8080});
for (;;) {
ip::tcp::socket socket(ioc);
acceptor.accept(socket);
std::make_shared<logging_service>(ioc, std::move(socket))->run();
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << "\n";
}
}



