DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_multi_threaded_server

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

Legacy: examples_socket/multi_threaded_server/client.cpp, examples_socket/multi_threaded_server/m_thread.cpp, examples_socket/multi_threaded_server/server.cpp · Modern: examples_modern/socket/multi_threaded_server/modern.cpp

Modern equivalent of the multi-threaded client and server. The legacy server derives from gxThread, keeps a thrPool of client threads, and is stopped by canceling the thread blocked in accept(). Here:

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.
sSleep(), mSleep(), uSleep(), nSleep()std::this_thread::sleep_for(1s), (500ms), (100us), (100ns)C++11 (literals C++14)The unit is part of the std::chrono duration type.
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.
SetWidth(), SetFill(), Precision(), sprintf()std::format("{:*>10} {:.3f}", ...)C++20C++17 and older: <iomanip> setw, setfill, setprecision.
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/multi_threaded_server/client.cpp 203 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 <stdio.h>
#include "m_thread.h"

// --------------------------------------------------------------
// Globals
// --------------------------------------------------------------
char *server_ip;
gxsPort_t port = 7;
int echo_loop = 1;
int num_clients = 1;
int packet_size = 1500;
// --------------------------------------------------------------

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

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

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

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;
}

void *EchoThread::ThreadEntryRoutine(gxThread_t *thread)
{
  // Extract the client number from the thread parameter
  int num = *((int *)thread->GetThreadParm());
  char sbuf[255];
  sprintf(sbuf, "%i", num);

  PrintMessage("Constructing stream client ", sbuf);
  gxSocket client(SOCK_STREAM, port, server_ip);
  if(!client) {
    CheckSocketError(&client);
    return (void *)0;
  }

  // Connect to the server
  if(client.Connect() < 0) {
    CheckSocketError(&client, "Could not connect to the server");
    client.Close();
    return (void *)0;
  }

  char *packet = new char[packet_size];

  while(echo_loop) {
    // Blocking write used to send the packet to the server
    int rv = client.Send((char *)packet, packet_size);
    if(rv < 0) {
      if(client.GetSocketError() != gxSOCKET_TRANSMIT_ERROR) {
	CheckSocketError(&client, "Error writing to server socket");
      }
      else {
	PrintMessage("Server has disconnected during a socket write");
      }
      delete[] packet;
      client.Close();
      return (void *)0;
    }
    
    int bytes_read = 0; // Total bytes read
 
    // Read the bytes sent back from the server
    while(bytes_read < packet_size) {

      // Block until the server sends some data
      // 10/31/2026: 0 (the server closed) looped for ever
      rv = client.RawRead((char *)packet, packet_size);
      if(rv <= 0) {
	if(client.GetSocketError() != gxSOCKET_RECEIVE_ERROR) {
	  CheckSocketError(&client, "Error reading from server socket");
	}
	else {
	  PrintMessage("Server has disconnected during a socket read");
	}
	delete[] packet;
	client.Close();
	return (void *)0;
      }
      bytes_read += rv;
    }

    // Client send and receive complete
    
    // Sleep to conserve CPU resources
    mSleep(500); // Sleep for 500 ms before sending the next packet
  }

  client.Close();
  delete[] packet;
  return (void *)0;
}

int main(int argc, char **argv)
{
  if((argc < 2) || (argc > 5)) {
    cerr << "Usage: " << argv[0] 
	 << " server [port] [num_clients] [packet_size]" << "\n" << flush;
    return 1;
  }

  server_ip = argv[1];
  if(argc >= 3) port = (unsigned short)atoi(argv[2]);
  if(argc >= 4) num_clients = (unsigned short)atoi(argv[3]);
  if(argc == 5) packet_size = (unsigned short)atoi(argv[4]);

  cout << "Multi-client connection and bandwidth tester" << "\n" << flush;
  cout << "Connecting " << num_clients << " to " << server_ip << "\n" << flush;
  cout << "Data packet size minus overhead: " << packet_size << "\n" << flush;
  cout << "\n" << flush;
  cout << "Press Enter to start test or C-Ctrl to exit" << "\n" << flush;
  cout << "Enter quit to exit program after the entering connection test" 
       << "\n" << flush;

  EchoThread client;
  thrPool *client_pool = new thrPool;
  if(!client_pool) {
    cout << "Could not allocate memory for the client thread pool" << "\n" 
	 << flush;
    cout << "Exiting..." << "\n" << flush;
    return 1;
  }

  for(int i = 0; i < num_clients; i++) {
    gxThread_t *client_thread = client.CreateThread(client_pool, 
						    (void *)&i);
    if(client_thread->GetThreadError() != gxTHREAD_NO_ERROR) {
      cout << client_thread->ThreadExceptionMessage() << "\n" << flush;
      echo_loop = 0;
      client.DestroyThreadPool(client_pool, 0);
      return 1;
    }
    client.sSleep(1);
  }
  
  ConsoleThread console;
  gxThread_t *console_thread = console.CreateThread();
  if(console_thread->GetThreadError() != gxTHREAD_NO_ERROR) {
    cout << console_thread->ThreadExceptionMessage() << "\n" << flush;
    echo_loop = 0;
    client.DestroyThreadPool(client_pool, 0);
    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 all client threads..." << "\n" << flush;
  echo_loop = 0;
  client.DestroyThreadPool(client_pool, 0);

  cout << "Exiting..." << "\n" << flush;
  delete console_thread;
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/multi_threaded_server/m_thread.cpp 282 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 "m_thread.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;
  echo_loop = 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("Connecting to client: ", 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.
{
  const int buf_len = 1500; // Receive buffer size
  char echo_buffer[buf_len];

  while(servercfg->echo_loop) {
    // Block until the client sends some data
    int br = RawRead(s->client_socket, echo_buffer, buf_len);
    if(br < 0) {
      if(GetSocketError() != gxSOCKET_RECEIVE_ERROR) {
	CheckSocketError((gxSocket *)this, "Error reading client socket");
      }
      else {
	PrintMessage("Client has disconnected during a socket read");
      }
      return;
    }
    
    while(br > 0) {
      // Echo the message back to the client
      int bm = RawWrite(s->client_socket, echo_buffer, br);
      if(bm < 0) {
	if(GetSocketError() != gxSOCKET_TRANSMIT_ERROR) {
	  CheckSocketError((gxSocket *)this, "Error writing to client socket");
	}
	else {
	  PrintMessage("Client has disconnected during a socket write");
	}
	return;
      }
      
      // Keep receiving data from the client
      br = RawRead(s->client_socket, echo_buffer, buf_len);
      if(br < 0) {
	if(GetSocketError() != gxSOCKET_RECEIVE_ERROR) {
	  CheckSocketError((gxSocket *)this, "Error reading client socket");
	}
	else {
	  PrintMessage("Client has disconnected during a socket read");
	}
	return;
      }
    }
  }
  PrintMessage("Client has disconnected");
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/multi_threaded_server/server.cpp 125 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 "m_thread.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 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 multi-threaded 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;
  }

  cout << "Stopping the server thread..." << "\n" << flush;
  servercfg->accept_clients = 0;
  servercfg->echo_loop = 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 canel 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/multi_threaded_server/m_thread.h 101 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; // Ture while accepting 
  int echo_loop;      // True to keep all connection persistent

  // 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/multi_threaded_server/modern.cpp 89 lines
#include <atomic>
#include <future>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

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

using namespace modern_net;

class EchoServer {
public:
  int start() {
    port_ = listen_loopback(listener_, 16);
    if(port_ > 0) acceptor_ = std::jthread([this](std::stop_token st) { accept_loop(st); });
    return port_;
  }
  int connections() const { return connections_; }
  ~EchoServer() {
    acceptor_.request_stop();
    acceptor_.join();
    for(auto &w : workers_) w.request_stop();
  } // ~vector<jthread> joins the workers

private:
  void accept_loop(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) continue;
      connections_++;
      workers_.emplace_back([this, c](std::stop_token wst) { serve(wst, c); });
    }
  }
  void serve(std::stop_token st, gxsSocket_t c) {   // One client
    std::string buf(1024, '\0');
    while(!st.stop_requested()) {
      if(listener_.ReadSelect(c, 0, 100000) <= 0) continue;
      int n = listener_.RawRead(c, buf.data(), int(buf.size()));
      if(n <= 0) break;
      std::string reply = "ECHO " + buf.substr(0, std::size_t(n));
      listener_.Send(c, reply.data(), int(reply.size()));
    }
    gxsSocket_t s = c;
    listener_.Close(s);
  }
  gxSocket listener_;
  int port_ = -1;
  std::atomic<int> connections_{0};
  std::vector<std::jthread> workers_;   // Only the acceptor thread adds
  std::jthread acceptor_;               // Declared last: stopped first
};

int main()
{
  ignore_sigpipe();
  SocketLibrary lib;
  EchoServer server;
  int port = server.start();
  if(!lib || port < 0) { std::cout << "Cannot start the server\n"; return 1; }
  std::cout << "Server listening on 127.0.0.1:" << port << "\n";

  const int NUM_CLIENTS = 8;
  std::vector<std::future<bool>> clients;
  for(int i = 0; i < NUM_CLIENTS; i++) {
    clients.push_back(std::async(std::launch::async, [port, i] {
      gxSocket c(SOCK_STREAM, gxsPort_t(port), const_cast<char *>("127.0.0.1"));
      if(c.Connect() < 0) return false;
      std::string msg = "client " + std::to_string(i) + "\n";
      c.Send(msg.data(), int(msg.size()));
      std::string reply(64, '\0');
      int n = c.Recv(reply.data(), int(reply.size()), 5, 0);
      c.Close();
      return n > 0 && reply.substr(0, std::size_t(n)) == "ECHO " + msg;
    }));
  }
  int ok = 0;
  for(auto &f : clients) ok += f.get();
  std::cout << ok << " of " << NUM_CLIENTS << " clients got their echo, "
            << server.connections() << " connections accepted\n";
  return ok == NUM_CLIENTS ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- 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_multi_threaded_server
./build-modern/socket_multi_threaded_server

Output of the modern program

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

Server listening on 127.0.0.1:53783
8 of 8 clients got their echo, 8 connections accepted