DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_http_server

C++20 or laterDataReel 6.4.3Portable C++ (tested on Linux)

Legacy: examples_socket/http_server/httpserv.cpp, examples_socket/http_server/server.cpp · Modern: examples_modern/socket/http_server/modern.cpp

Modern equivalent of the multi-threaded HTTP server framework. The request line is parsed with std::string_view (method, path, version) with no copies and no fixed buffers; the documents are a std::unordered_map from path to body; the response is built with C++20 std::format. Each connection is handled by a std::jthread, the acceptor checks a std::stop_token between select() timeouts, and the server stops when the object is destroyed. main() runs a few requests against it with a plain gxSocket client and checks the status codes.

Legacy calls in this program

LegacyModern C++StandardNotes
gxThread subclass, CreateThread()std::thread t(callable, args...)C++11Any function, lambda or functor runs in the thread; arguments are copied with their types (no void *).
JoinThread()t.join(); std::future::get()C++11join() waits; a std::async future's get() also returns the result.
CancelThread(), ThreadCleanupHandler()std::jthread::request_stop() + std::stop_token; cleanup in a destructorC++20Cancellation is cooperative: the thread checks stop_requested() or waits on a condition_variable_any with the token.
thrPool, CreateThreadPool()a small pool: std::thread workers, std::queue, std::condition_variable, std::packaged_taskC++11 (C++17 invoke_result)submit() returns a std::future; the destructor joins the workers.
gxMutex, MutexLock()/MutexUnlock()std::mutex + std::scoped_lock / std::lock_guard / std::unique_lockC++11 / C++17The lock is released by a destructor on every path, so a return cannot leave it locked.
gxCondition, ConditionWait()/ConditionSignal()std::condition_variable wait(lock, predicate) / notify_one()C++11The predicate form handles spurious wake ups.
Atoi(), Atol(), Atof(), atoi()std::from_chars() into std::optional<T>; std::stoi()C++17Overflow and junk are reported, not turned into 0.
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
gxSocketkeep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeoutsC++20Stopping is a request, not a canceled thread blocked in accept().

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/http_server/httpserv.cpp 269 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include <string.h>
#include "httpserv.h"

// --------------------------------------------------------------
// Globals variable initialzation
// --------------------------------------------------------------
ServerConfig ServerConfigSruct;
ServerConfig *servercfg = &ServerConfigSruct;
// --------------------------------------------------------------

int CheckSocketError(gxSocket *s, const char *mesg, int report_error)
// Test the socket for an error condition and report the message
// if the "report_error" variable is true. The "mesg" string is used
// display a message with the reported error. Returns true if an
// error was detected for false of no errors where detected. 
{
  if(s->GetSocketError() == gxSOCKET_NO_ERROR) {
    // No socket errors reported
    return 0;
  }
  if(report_error) { // Reporting the error to an output device
    if(mesg) {
      PrintMessage(mesg, "\n", s->SocketExceptionMessage());
    }
    else {
      PrintMessage(s->SocketExceptionMessage());
    }
  }
  return 1;
}

int CheckThreadError(gxThread_t *thread, const char *mesg, int report_error)
// Test the thread for an error condition and report the message
// if the "report_error" variable is true. The "mesg" string is used
// display a message with the reported error. Returns true if an
// error was detected for false of no errors where detected. 
{
  if(thread->GetThreadError() == gxTHREAD_NO_ERROR) {
    // No thread errors reported
    return 0;
  }
  if(report_error) { // Reporting the error to an output device
    if(mesg) {
      PrintMessage(mesg, "\n", thread->ThreadExceptionMessage()); 
    }
    else {
      PrintMessage(thread->ThreadExceptionMessage());
    }
  }
  return 1;
}

void ReportError(const char *s1, const char *s2, const char *s3)
// Thread safe error reporting function.
{
  PrintMessage(s1, s2, s3);
}

void PrintMessage(const char *s1, const char *s2, const char *s3)
// Thread safe write function that will not allow access to
// the critical section until the write operation is complete.
{
  servercfg->display_lock.MutexLock();

  // Ensure that all threads have finished writing to the device
  int num_try = 0;
  while(servercfg->display_is_locked != 0) {
    // Block this thread from its own execution if a another thread
    // is writing to the device
    if(++num_try < DISPLAY_THREAD_RETRIES) {
      servercfg->display_cond.ConditionWait(&servercfg->display_lock);
    }
    else {
      return; // Could not write string to the device
    }
  }

  // Tell other threads to wait until write is complete
  servercfg->display_is_locked = 1; 

  // ********** Enter Critical Section ******************* //
  GXSTD::cout << "\n";
  if(s1) GXSTD::cout << s1;
  if(s2) GXSTD::cout << s2;
  if(s3) GXSTD::cout << s3;
  GXSTD::cout << "\n";
  GXSTD::cout.flush(); // Flush the ostream buffer to the stdio
  // ********** Leave Critical Section ******************* //

  // Tell other threads that this write is complete
  servercfg->display_is_locked = 0; 
 
  // Wake up the next thread waiting on this condition
  servercfg->display_cond.ConditionSignal();
  servercfg->display_lock.MutexUnlock();
}

ServerConfig::ServerConfig()
{
  port = 80;
  accept_clients = 1;
  display_is_locked = 0;
  client_request_pool = new thrPool;
}

ServerConfig::~ServerConfig()
{
  if(client_request_pool) delete client_request_pool;
}

int ServerThread::InitServer(int max_connections)
// Initialize the server. Returns a non-zero value if any
// errors ocurr.
{
  if(InitSocketLibrary() == 0) {
    if(InitSocket(SOCK_STREAM, servercfg->port) < 0) return 1;
  }
  else {
    return 1;
  }

  // Bind the name to the socket
  if(Bind() < 0) {
    CheckSocketError((gxSocket *)this, "Error initializing server"); 
    Close();
    return 1;
  }
    
  // Listen for connections with a specified backlog
  if(Listen(max_connections) < 0) {
    CheckSocketError((gxSocket *)this, "Error initializing server");
    Close();
    return 1;
  }

  return 0;
}

void *ServerThread::ThreadEntryRoutine(gxThread_t *thread)
{
  while(servercfg->accept_clients) { // Loop accepting client connections

    // Block the server until a client requests service
    if(Accept() < 0) continue;

    // NOTE: Getting client info for statistical purposes only
    char client_name[gxsMAX_NAME_LEN]; int r_port = -1;
    GetClientInfo(client_name, r_port);
    PrintMessage("Received client request from ", client_name);

    ClientSocket_t *s = new ClientSocket_t;
    if(!s) {
      ReportError("A fatal memory allocation error occurred\n \
Shutting down the server");
      CloseSocket();
      return (void *)0;
    }
    
    // Record the file descriptor assigned by the Operating System
    s->client_socket = GetRemoteSocket();

    // Destroy all the client threads that have exited
    RebuildThreadPool(servercfg->client_request_pool);

    // Create thread per cleint
    gxThread_t *rthread = \
      request_thread.CreateThread(servercfg->client_request_pool, (void *)s);
    if(CheckThreadError(rthread, "Error starting client request thread")) {
      delete s;
      return (void *)0;
    }
  }

  return (void *)0;
}

void ServerThread::ThreadExitRoutine(gxThread_t *thread)
// Thread exit function used to close the server thread.
{
  CloseSocket(); // Close the server side socket
}

void ServerThread::ThreadCleanupHandler(gxThread_t *thread)
// Thread cleanup handler used in the event that the thread is
// canceled.
{
  CloseSocket(); // Close the server side socket
}

void *ClientRequestThread::ThreadEntryRoutine(gxThread_t *thread)
{
  // Extract the client socket from the thread parameter
  ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm();
  
  // Process the client request
  HandleClientRequest(s);

  return (void *)0;
}

void ClientRequestThread::ThreadExitRoutine(gxThread_t *thread)
// Thread exit function used to close the client thread.
{
  // Extract the client socket from the thread parameter
  ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm();

  // Close the client socket and free its resources
  Close(s->client_socket);
  delete s;
}

void ClientRequestThread::ThreadCleanupHandler(gxThread_t *thread)
// Thread cleanup handler used in the event that the thread is
// canceled.
{
  // Extract the client socket from the thread parameter
  ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm();

  // Close the client socket and free its resources
  Close(s->client_socket);
  delete s;
}

void ClientRequestThread::HandleClientRequest(ClientSocket_t *s)
// Function used to handle a client request.
{
  // NOTE: The demo processes a single HTTP GET request per client
  const int rxbuf = 1024;
  char request[rxbuf];

  // Block until the client sends some data
  // 10/31/2026: Read at most rxbuf-1 bytes. request[rv] = 0 wrote one
  // byte past the end of request when a client sent 1024 bytes or more.
  int rv = RawRead(s->client_socket, request, rxbuf - 1);
  if(CheckSocketError((gxSocket *)this, "Error reading client request")) {
    return;
  }
  if(rv < 0) return;

  request[rv] = 0; // Null terminate the request string

  // At this point we need to parse the client request and process it.
  // For simplicity sake these operations have been omitted.
  // ... (parsing operation)
  // ... (processing operation)

  // Simply send a test page (with a header) back to the client.
  const char *test_page = "HTTP/1.0 200 OK\r\nServer: gxThread\r\nConnection: \
close\r\n\r\n<HTML>\n<HEAD>\n<TITLE> gxThread Test Page </TITLE>\n</HEAD>\
<BODY><CENTER><H1>gxThread Test Page</H1></CENTER><HR><PRE>Response from the \
multi-threaded HTTP server</PRE><HR><CENTER>End of document</CENTER>\n</BODY>\
\n</HTML>";

  // Blocking send that will not return until all bytes are written  
  Send(s->client_socket, test_page, strlen(test_page));
  CheckSocketError((gxSocket *)this, "Error sending page to client");
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/http_server/server.cpp 124 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include <string.h>
#include <stdlib.h>
#include "httpserv.h"

class ConsoleThread : public gxThread
{
public:
  ConsoleThread() { }
  ~ConsoleThread() { }

private:
  void *ThreadEntryRoutine(gxThread_t *thread);
};

void *ConsoleThread::ThreadEntryRoutine(gxThread_t *thread)
{
  const int cmd_len = 255;
  char sbuf[cmd_len];
  
  while(1) {
    for(int i = 0; i < cmd_len; i++) sbuf[i] = 0;
    // 10/14/2026: Limit the read to the buffer size and stop at the end of
    // input (the loop used to overflow sbuf on long input and spin forever
    // when stdin was closed)
    cin.width(cmd_len);
    if(!(cin >> sbuf)) break;
    if(strcmp(sbuf, "quit") == 0) break;
    if(strcmp(sbuf, "exit") == 0) break;
    cout << "Invalid command" << "\n" << flush;
    cout << "Enter quit to exit" << "\n" << flush;
  }
  return (void *)0;
}

int main(int argc, char **argv)
{
  // Check arguments. Should be only one: the port number to bind to.
  if(argc != 2) {
    cerr << "Usage: " << argv[0] << " port" << "\n" << flush;
    return 1;
  }

  ServerThread server;
  servercfg->port = (gxsPort_t) atoi(argv[1]);

  cout << "Initializing HTTP server..." << "\n" << flush;
  int rv = server.InitServer(servercfg->port);
  if(rv != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  // Get the host name assigned to this machine
  char hostname[gxsMAX_NAME_LEN];
  rv = server.GetHostName(hostname);
  if(rv != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  cout << "Opening server on host " << hostname << "\n" << flush;
  cout << "Enter quit to exit" << "\n" << flush;
  cout << "\n" << flush;
  
  cout << "Listening on port " << servercfg->port << "\n" << flush;
  cout.flush();

 gxThread_t *server_thread = server.CreateThread();
  if(server_thread->GetThreadError() != gxTHREAD_NO_ERROR) {
    cout << server_thread->ThreadExceptionMessage() << "\n" << flush;
    return 1;
  }
  
  ConsoleThread console;
  gxThread_t *console_thread = console.CreateThread();
  if(console_thread->GetThreadError() != gxTHREAD_NO_ERROR) {
    cout << console_thread->ThreadExceptionMessage() << "\n" << flush;
    return 1;
  }
    
  if(console.JoinThread(console_thread) != 0) {
    cout << "Could not join the console thread" << "\n" << flush;
  }

  // Destroy the serial port receiver thread
  cout << "Stopping the server thread..." << "\n" << flush;
  servercfg->accept_clients = 0;

  // Cannot the server thread due to the blocking accept() function, so
  // cancel the thread before it is destroyed
  server.CancelThread(server_thread);
  if(server_thread->GetThreadState() == gxTHREAD_STATE_CANCELED) {
    cout << "The server thread was stopped" << "\n" << flush;
  }
  else {
    cout << "Could not cancel the server thread" << "\n" << flush;
  }

  if(server.JoinThread(server_thread) != 0) {
    cout << "Could not join the server thread" << "\n" << flush;
  }
    
  delete server_thread;
  delete console_thread;

  cout << "Exiting..." << "\n" << flush;
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //


  
examples_socket/http_server/httpserv.h 100 lines
#ifndef __GX_S_MTHREAD_SERVER_HPP__
#define __GX_S_MTHREAD_SERVER_HPP__

#include "gxdlcode.h"

#include "gxmutex.h"
#include "gxcond.h"
#include "gxthread.h"
#include "gxsocket.h"

// --------------------------------------------------------------
// Constants
// --------------------------------------------------------------
// Thread constants
const int DISPLAY_THREAD_RETRIES = 3;
// --------------------------------------------------------------

// Server configuration
struct  ServerConfig {
  ServerConfig();
  ~ServerConfig();
  
  // Server configuration variables
  gxsPort_t port;     // Server's port number
  int accept_clients; // True while accepting 

  // gxThread variables
  thrPool *client_request_pool; // Worker threads processing client requests

  // gxThread synchronization interface
  gxMutex display_lock;      // Mutex object used to lock the display
  gxCondition display_cond;  // Condition variable used with the display lock
  int display_is_locked;     // Display lock Boolean predicate
};

// Client socket type used to associate client sockets other
// data types.
struct ClientSocket_t
{
  gxsSocket_t client_socket; // Client socket
};

class ClientRequestThread : public gxSocket, public gxThread
{
public:
  ClientRequestThread() { }
  ~ClientRequestThread() { }

public: // Client routines
  void HandleClientRequest(ClientSocket_t *s);

private: // gxThread Interface
  void *ThreadEntryRoutine(gxThread_t *thread);
  void ThreadExitRoutine(gxThread_t *thread);
  void ThreadCleanupHandler(gxThread_t *thread);
};

class ServerThread : public gxSocket, public gxThread
{
public:
  ServerThread() { }
  ~ServerThread() { }

public: // Server functions
  int InitServer(int max_connections = SOMAXCONN);

private: // gxThread Interface
  void *ThreadEntryRoutine(gxThread_t *thread);
  void ThreadExitRoutine(gxThread_t *thread);
  void ThreadCleanupHandler(gxThread_t *thread);
  
public: // Server data members
  ClientRequestThread request_thread;
};

// --------------------------------------------------------------
// Standalone functions
// --------------------------------------------------------------
void PrintMessage(const char *s1 = " ", const char *s2 = " ", 
		  const char *s3 = " ");
void ReportError(const char *s1 = " ", const char *s2 = " ", 
		 const char *s3 = " ");
int CheckSocketError(gxSocket *s, const char *mesg = 0, 
		     int report_error = 1);
int CheckThreadError(gxThread_t *thread, const char *mesg = 0, 
		     int report_error = 1);
// --------------------------------------------------------------

// --------------------------------------------------------------
// Globals configuration variables
// --------------------------------------------------------------
extern ServerConfig ServerConfigSruct;
extern ServerConfig *servercfg;
// --------------------------------------------------------------

#endif // __GX_S_MTHREAD_SERVER_HPP__
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/http_server/modern.cpp 115 lines
#include <format>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <thread>
#include <unordered_map>
#include <vector>

#include "../common/modern_net.h"

using namespace modern_net;

struct Request { std::string_view method, path, version; };

std::optional<Request> parse_request_line(std::string_view text)
{
  auto eol = text.find("\r\n");
  if(eol == std::string_view::npos) return std::nullopt;
  std::string_view line = text.substr(0, eol);
  auto sp1 = line.find(' '), sp2 = line.rfind(' ');
  if(sp1 == std::string_view::npos || sp2 == sp1) return std::nullopt;
  Request r{line.substr(0, sp1), line.substr(sp1 + 1, sp2 - sp1 - 1), line.substr(sp2 + 1)};
  if(!r.version.starts_with("HTTP/") || !r.path.starts_with('/')) return std::nullopt;
  return r;
}

class HttpServer {
public:
  explicit HttpServer(std::unordered_map<std::string, std::string> docs) : docs_(std::move(docs)) {}
  int start() {
    port_ = listen_loopback(listener_, 16);
    if(port_ > 0) acceptor_ = std::jthread([this](std::stop_token st) { run(st); });
    return port_;
  }
  ~HttpServer() { acceptor_.request_stop(); acceptor_.join(); }

private:
  void run(std::stop_token st) {
    while(!st.stop_requested()) {
      if(listener_.ReadSelect(listener_.GetSocket(), 0, 100000) <= 0) continue;
      gxsSocketAddress sa{};
      gxsSocket_t c = listener_.Accept(listener_.GetSocket(), &sa);
      if(c >= 0) workers_.emplace_back([this, c] { handle(c); });
    }
  }
  void handle(gxsSocket_t c) {
    std::string in;
    std::string buf(1024, '\0');
    while(in.find("\r\n\r\n") == std::string::npos && in.size() < 8192) {
      if(listener_.ReadSelect(c, 5, 0) <= 0) break;
      int n = listener_.RawRead(c, buf.data(), int(buf.size()));
      if(n <= 0) break;
      in.append(buf, 0, std::size_t(n));
    }
    int status = 400;
    std::string_view reason = "Bad Request", body = "bad request\n";
    if(auto req = parse_request_line(in)) {
      if(req->method != "GET") { status = 501; reason = "Not Implemented"; body = "GET only\n"; }
      else if(auto it = docs_.find(std::string(req->path)); it != docs_.end()) {
        status = 200; reason = "OK"; body = it->second;
      }
      else { status = 404; reason = "Not Found"; body = "not found\n"; }
    }
    std::string out = std::format("HTTP/1.0 {} {}\r\nContent-Type: text/plain\r\n"
                                  "Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                                  status, reason, body.size(), body);
    listener_.Send(c, out.data(), int(out.size()));
    gxsSocket_t s = c;
    listener_.Close(s);
  }
  gxSocket listener_;
  int port_ = -1;
  std::unordered_map<std::string, std::string> docs_;
  std::vector<std::jthread> workers_;
  std::jthread acceptor_;
};

std::string get(int port, std::string_view request)
{
  gxSocket c(SOCK_STREAM, gxsPort_t(port), const_cast<char *>("127.0.0.1"));
  if(c.Connect() < 0) return {};
  c.Send(request.data(), int(request.size()));
  std::string reply, buf(4096, '\0');
  for(int n; (n = c.Recv(buf.data(), int(buf.size()), 5, 0)) > 0;) reply.append(buf, 0, std::size_t(n));
  return reply;
}

int main()
{
  ignore_sigpipe();
  SocketLibrary lib;
  HttpServer server({{"/", "Welcome to the modern DataReel HTTP server\n"},
                     {"/status", "OK\n"}});
  int port = server.start();
  if(!lib || port < 0) return 1;
  struct Case { std::string_view request; std::string_view expect; };
  int failures = 0;
  for(auto [request, expect] : {Case{"GET / HTTP/1.0\r\n\r\n", "HTTP/1.0 200"},
                                Case{"GET /status HTTP/1.0\r\n\r\n", "HTTP/1.0 200"},
                                Case{"GET /missing HTTP/1.0\r\n\r\n", "HTTP/1.0 404"},
                                Case{"POST / HTTP/1.0\r\n\r\n", "HTTP/1.0 501"},
                                Case{"garbage\r\n\r\n", "HTTP/1.0 400"}}) {
    std::string reply = get(port, request);
    bool ok = reply.starts_with(expect);
    std::cout << (ok ? "PASS " : "FAIL ") << request.substr(0, request.find('\r'))
              << " -> " << reply.substr(0, reply.find('\r')) << "\n";
    failures += !ok;
  }
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H
#define MODERN_NET_H

#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <vector>
#if !defined(_WIN32)
#include <arpa/inet.h>
#include <csignal>
#endif

#include "gxsocket.h"

namespace modern_net {

inline void ignore_sigpipe()
{
#if !defined(_WIN32)
  std::signal(SIGPIPE, SIG_IGN);
#endif
}

class SocketLibrary {                    // RAII for Winsock and friends
public:
  SocketLibrary() { ok_ = probe_.InitSocketLibrary() == 0; }
  ~SocketLibrary() { probe_.ReleaseSocketLibrary(); }
  SocketLibrary(const SocketLibrary &) = delete;
  SocketLibrary &operator=(const SocketLibrary &) = delete;
  explicit operator bool() const { return ok_; }
private:
  gxSocket probe_;
  bool ok_ = false;
};

inline int bound_port(gxSocket &s)       // After Bind() to port 0
{
  if(s.GetSockName() < 0) return -1;
  return int(ntohs(s.sin.sin_port));
}

// Opens a listening socket on 127.0.0.1 and a free port. Returns the
// port or -1.
inline int listen_loopback(gxSocket &s, int backlog = 5)
{
  if(s.InitSocket(SOCK_STREAM, 0, const_cast<char *>("127.0.0.1")) < 0) return -1;
  if(s.Bind() < 0 || s.Listen(backlog) < 0) return -1;
  return bound_port(s);
}

class FakeServer {
public:
  enum class Kind { Send, Sleep, ReadLine, ReadHeader, ReadData, DataListen, DataSend };
  struct Step { Kind kind; std::string data; };

  FakeServer &send(std::string s) { steps_.push_back({Kind::Send, std::move(s)}); return *this; }
  FakeServer &sleep(int ms) { steps_.push_back({Kind::Sleep, std::to_string(ms)}); return *this; }
  FakeServer &read_line() { steps_.push_back({Kind::ReadLine, {}}); return *this; }
  FakeServer &read_header() { steps_.push_back({Kind::ReadHeader, {}}); return *this; }
  FakeServer &read_data() { steps_.push_back({Kind::ReadData, {}}); return *this; }
  FakeServer &reply(std::string s) { read_line(); return send(std::move(s)); }
  FakeServer &data_listen() { steps_.push_back({Kind::DataListen, {}}); return *this; }
  FakeServer &data_send(std::string s) { steps_.push_back({Kind::DataSend, std::move(s)}); return *this; }

  // Starts the script; returns the port or -1
  int start() {
    port_ = listen_loopback(listener_, 1);
    if(port_ > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); });
    return port_;
  }
  void join() { if(worker_.joinable()) worker_.join(); }
  const std::string &received() const { return received_; } // After join()
  ~FakeServer() { join(); }

private:
  bool wait_read(gxSocket &s, gxsSocket_t fd, std::stop_token &st) {
    for(int i = 0; i < 50 && !st.stop_requested(); i++)  // Up to 5 s
      if(s.ReadSelect(fd, 0, 100000) > 0) return true;
    return false;
  }
  void run(std::stop_token st) {
    if(!wait_read(listener_, listener_.GetSocket(), st) || listener_.Accept() < 0) {
      listener_.Close();
      return;
    }
    gxsSocket_t c = listener_.GetRemoteSocket();
    for(const Step &step : steps_) {
      if(step.kind == Kind::Send) {
        std::string d = step.data;
        if(auto p = d.find("%PORT%"); p != std::string::npos)
          d.replace(p, 6, std::to_string(data_port_ / 256) + "," + std::to_string(data_port_ % 256));
        if(listener_.Send(c, d.data(), int(d.size())) < 0) break;
      }
      else if(step.kind == Kind::Sleep) {
        std::this_thread::sleep_for(std::chrono::milliseconds(std::stoi(step.data)));
      }
      else if(step.kind == Kind::DataListen) {
        data_port_ = listen_loopback(data_, 1);
      }
      else if(step.kind == Kind::DataSend) {
        if(wait_read(data_, data_.GetSocket(), st) && data_.Accept() >= 0) {
          gxsSocket_t d = data_.GetRemoteSocket();
          data_.Send(d, step.data.data(), int(step.data.size()));
          data_.Close(d);
        }
        data_.Close();
      }
      else {                                // One of the reads
        std::string got;
        auto ends_with = [&got](std::string_view e) { return got.ends_with(e); };
        while(wait_read(listener_, c, st)) {
          char ch;
          if(listener_.RawRead(c, &ch, 1) != 1) break;
          got += ch;
          if(step.kind == Kind::ReadLine && ch == '\n') break;
          if(step.kind == Kind::ReadHeader && ends_with("\r\n\r\n")) break;
          if(step.kind == Kind::ReadData && ends_with("\r\n.\r\n")) break;
        }
        received_ += got;
        if(got.empty()) break;              // The client closed
      }
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    listener_.Close(c);
    listener_.Close();
  }

  gxSocket listener_, data_;
  std::vector<Step> steps_;
  std::string received_;
  int port_ = -1, data_port_ = 0;
  std::jthread worker_;
};

} // namespace modern_net

#endif // MODERN_NET_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20
cmake --build build-modern --target socket_http_server
./build-modern/socket_http_server

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

PASS GET / HTTP/1.0 -> HTTP/1.0 200 OK
PASS GET /status HTTP/1.0 -> HTTP/1.0 200 OK
PASS GET /missing HTTP/1.0 -> HTTP/1.0 404 Not Found
PASS POST / HTTP/1.0 -> HTTP/1.0 501 Not Implemented
PASS garbage -> HTTP/1.0 400 Bad Request