DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_socket_cache

C++20 or laterDataReel 6.4.3POSIX (Linux, UNIX)

Legacy: examples_socket/socket_cache/client.cpp, examples_socket/socket_cache/gxsfile.cpp, examples_socket/socket_cache/server.cpp · Modern: examples_modern/socket/socket_cache/modern.cpp

Modern equivalent of the device cache client and server, which move a file through cache buckets over a gxStream connection. This program moves a file as length-prefixed blocks over a TCP stream on 127.0.0.1 (common/block_frame.h): the client reads the file with std::ifstream into a std::vector<std::byte> bucket and sends each one as a block; the server, a std::jthread, writes each block it receives with std::ofstream and stops at an empty block. The server checks every block length against a maximum before it allocates. Both files are compared at the end.

For production transfers between DataReel programs keep gxStream: it has the mutual TLS client authentication of the legacy server (--client-ca, --allow-fingerprint, --allow-cn); this example shows the modern C++ for the data path only.

Usage: modern [FILE] (default: this program's own executable)

Legacy calls in this program

LegacyModern C++StandardNotes
MemoryBufferstd::vector<unsigned char> or std::vector<std::byte>; std::span for viewsC++98 / C++17 / C++20std::search finds a byte pattern; std::fill for MemSet().
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98
gxDeviceCache, gxDeviceBucketCachestreams buffer themselves: std::filesystem::copy_file(), out << in.rdbuf()C++17
gxStream, gxDatagram blockskeep gxStream for mutual TLS; length-checked blocks with std::span, std::endian, std::optionalC++20

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/socket_cache/client.cpp 336 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 "gxsfile.h"

// 10/31/2026: Stream client options, see above
static const char *opt_ca = 0, *opt_cert = 0, *opt_key = 0;
static int opt_insecure = 0;

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

void ClearInputStream(istream &s)
{
  char c;
  s.clear();
  while(s.get(c) && c != '\n') { ; }
}

void InputString(char *mesg, MemoryBuffer &s)
{
  cout << mesg << ": ";
  char buf[255];
  for(int i = 0; i < 255; i++) buf[i] = 0;
  cin >> buf;
  s.Load(buf, (strlen(buf) + 1));
  s[s.length()] += '\0'; // Null terminate the string
}

void InputInt(char *mesg, int &i)
{
  cout << mesg << ": ";
  cin >> i;
  ClearInputStream(cin);
}

void Menu()
{
  cout << "\n" << flush;
  cout << "(?)   Display this menu" << "\n" << flush;
  cout << "(D)   Copy a disk file to a Datagram Socket" << "\n" << flush;
  cout << "(F)   Copy a disk file to another disk file" << "\n" << flush;
  cout << "(P)   Copy a disk file to a Serial port" << "\n" << flush;
  cout << "(Q)   Quit this program" << "\n" << flush;
  cout << "(S)   Copy a disk file to a Stream Socket" << "\n" << flush;
  cout << "\n" << flush;
}

void CopyFileToSerialPort(gxsFile *dev) 
{
  MemoryBuffer in, port;
  InputString("Enter the name of the serial device", port);
  InputString("Enter the name of file to copy", in);
  
  if(!dev->OpenInputFile(in)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }
  
  FAU_t byte_count = (FAU_t)0;
  gxSerialCommServer client;
  
  int rv = client.InitCommServer(port);
  if(rv != gxSerialComm::scomm_NO_ERROR) {
    cout << client.SerialCommExceptionMessage() << "\n" << flush;
    return;
  }
  
  if(!dev->CopyFileToSerialPort(&client, byte_count)) {
    cout << "Error copying file." << "\n" << flush;
    return;
  }
  
  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseInputFile();
  
  // Shutdown the server
  client.TerminateConnection();
  
  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void CopyFileToStreamSocket(gxsFile *dev)
{
  gxStream client;
  int port;
  MemoryBuffer in, host;

  InputString("Enter the name of the server", host);
  InputInt("Enter the server's port number", port);
  InputString("Enter the name of file to copy", in);

  if(!dev->OpenInputFile(in)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }

  FAU_t byte_count = (FAU_t)0;

  // 10/31/2026: TLS options
  if(opt_ca || opt_cert || opt_insecure) client.UseTLS(1);
  if(opt_ca) client.SetServerCAFile(opt_ca);
  if(opt_insecure) client.SetVerifyServer(0);
  if(opt_cert) client.SetClientCert(opt_cert, opt_key);

  if(client.StreamClient(port, host) != 0) {
    cout << client.SocketExceptionMessage() << "\n" << flush;
    if(*client.TLSError()) cout << client.TLSError() << "\n" << flush;
    client.Close();
    return;
  }
  
  if(!dev->CopyFileToStreamSocket(&client, byte_count)) {
    cout << "Error copying file." << "\n" << flush;
    return;
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseInputFile();
  
  // Shutdown the server
  client.TerminateConnection();
  
  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void CopyFileToFile(gxsFile *dev)
{
  MemoryBuffer in, out;
  
  InputString("Enter the name of the input file", in);
  
  if(!dev->OpenInputFile(in)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }
  
  InputString("Enter the name of the output file", out);
  
  if(!dev->OpenOutputFile(out)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }

  FAU_t byte_count = (FAU_t)0;

  if(!dev->CopyFileToFile(byte_count)) {
    cout << "Error copying file." << "\n" << flush;
    return;
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseInputFile(); dev->CloseOutputFile();
  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void CopyFileToDatagramSocket(gxsFile *dev)
{
  gxDatagram client;
  int port;
  MemoryBuffer in, host;

  InputString("Enter the name of the server", host);
  InputInt("Enter the server's port number", port);
  InputString("Enter the name of file to copy", in);
  
  if(!dev->OpenInputFile(in)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }

  FAU_t byte_count = (FAU_t)0;

  if(client.DatagramClient(port, host) != 0) {
    cout << client.SocketExceptionMessage() << "\n" << flush;
    client.Close();
    return;
  }

  if(!dev->CopyFileToDatagramSocket(&client, byte_count)) {
    cout << "Error copying file." << "\n" << flush;
    return;
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseInputFile();

  // Shutdown the server
  client.TerminateConnection();

  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void SetupClient(int client_type)
{
  int cache_size = 10;
  gxsFile dev(cache_size); // Device cache used to process a file

  cout << "Creating a device cache using " << cache_size 
       << " cache buckets." << "\n" << flush;
  cout << "Reserving " << (sizeof(gxDeviceBucket) * cache_size) 
       << " bytes of memory." << "\n" << flush;
  cout << "Number of cache buckets in use = " << dev.BucketsInUse() << "\n" 
       << flush;
  cout << "\n" << flush;
  
  switch(client_type) {
    case gxSOCKET_STREAM_CLIENT:
      CopyFileToStreamSocket(&dev);
      Menu();
      break;
      
    case gxSOCKET_DATAGRAM_CLIENT:
      CopyFileToDatagramSocket(&dev);
      Menu();
      break;

    case gxSOCKET_SERIAL_PORT_CLIENT:
      CopyFileToSerialPort(&dev);
      Menu();
      break;
      
    case gxSOCKET_LOCAL_FILE_SYSTEM:
      CopyFileToFile(&dev);
      Menu();
      break;
      
    default:
      break;
  }
}

int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  // 10/31/2026: Stream client options
  for(int i = 1; i < argc; i++) {
    if(strcmp(argv[i], "--ca") == 0 && i + 1 < argc) opt_ca = argv[++i];
    else if(strcmp(argv[i], "--insecure") == 0) opt_insecure = 1;
    else if(strcmp(argv[i], "--cert") == 0 && i + 1 < argc) opt_cert = argv[++i];
    else if(strcmp(argv[i], "--key") == 0 && i + 1 < argc) opt_key = argv[++i];
    else {
      cout << "Usage: " << argv[0] << " [--ca ca.pem] [--insecure]"
	   << " [--cert client.pem --key client.key]" << "\n" << flush;
      return 1;
    }
  }
  if((opt_cert == 0) != (opt_key == 0)) {
    cout << "--cert and --key go together" << "\n" << flush;
    return 1;
  }

  Menu();
  
  char key;
  int rv = 1;
  while(rv) {
    if (!cin) {
      ClearInputStream(cin);
      if (!cin) {
	cout << "Input stream error" << "\n" << flush;
	return 0;
      }
    }
    cout << "\n" << flush;
    cout << '>';
    cin >> key;

    if (!cin) continue;
    switch(key) {
      case 'd' : case 'D' : 
	ClearInputStream(cin);
	SetupClient(gxSOCKET_DATAGRAM_CLIENT);
	break;
	
      case 'f' : case 'F' : 
	ClearInputStream(cin);
	SetupClient(gxSOCKET_LOCAL_FILE_SYSTEM);
	break;
	
      case 'p' : case 'P' :
	ClearInputStream(cin);
	SetupClient(gxSOCKET_SERIAL_PORT_CLIENT);
	break;
	
      case 's' : case 'S' :
	ClearInputStream(cin);
	SetupClient(gxSOCKET_STREAM_CLIENT);
	break;

      case 'q' : case 'Q' :
	rv = 0;
	break;

      case '?' :
	Menu();
	break;

      default:
        cout << "Unrecognized command" << "\n" << flush;
	cout << "\n" << flush;
    }
  }
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/socket_cache/gxsfile.cpp 334 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 <sys/types.h>
#include <sys/stat.h>
#include "gxsfile.h"

gxsFile::gxsFile(int CacheSize) : cache(CacheSize) 
{ 
  ready_for_writing = ready_for_reading = 1;
  cache.Connect(this); 
  stream_sock = 0;
  datagram_sock = 0;
  serial_port = 0;
}

void gxsFile::Read(void *buf, unsigned Bytes, gxDeviceTypes dev) 
{
  switch(dev) {
    case gxDEVICE_DISK_FILE:
      if(!infile) { ready_for_reading = 0; return; }
      else { ready_for_reading = 1; }
      if(infile.df_Read((char *)buf, Bytes) != DiskFileB::df_NO_ERROR) {
	DeviceErrorHandler(infile.df_ExceptionMessage());
      }
      break;
      
    case  gxDEVICE_STREAM_SOCKET:
      if(!stream_sock) { ready_for_reading = 0; return; }
      else { ready_for_reading = 1; }
      // 10/31/2026: Read only as many bytes as the buffer holds; the
      // length in the header comes from the client
      if(stream_sock->ReadRemoteBlock((char *)buf, (int)Bytes, 
				      curr_stream_hdr) != 0)
	DeviceErrorHandler(stream_sock->SocketExceptionMessage());
      break;

    case gxDEVICE_DATAGRAM_SOCKET:
      if(!datagram_sock) { ready_for_reading = 0; return; }
      else { ready_for_reading = 1; }
      // 11/14/2026: Read only as many bytes as the buffer holds; the
      // length in the header comes from the client
      if(datagram_sock->ReadRemoteBlock((char *)buf, (int)Bytes,
					curr_datagram_hdr) != 0)
	DeviceErrorHandler(datagram_sock->SocketExceptionMessage());
      break;
      
    case gxDEVICE_SERIAL_PORT:
      if(!serial_port) {  ready_for_reading = 0; return; }
      else { ready_for_reading = 1; }
      // 11/14/2026: Sized read, the length comes from the peer
      if(serial_port->ReadBlock((char *)buf, (__ULWORD__)Bytes,
				curr_serial_hdr) != 0)
	DeviceErrorHandler(serial_port->SerialCommExceptionMessage());
      break;

    case gxDEVICE_NULL:
      break;
      
    default:
      break;
  }
}

void gxsFile::Write(const void *buf, unsigned Bytes, gxDeviceTypes dev) 
{
  switch(dev) {
    case gxDEVICE_CONSOLE:
      GXSTD::cout.write((char *)buf, Bytes);
      break;

    case gxDEVICE_DISK_FILE:
      if(!outfile) { ready_for_writing = 0; return; }
      else { ready_for_writing = 1; }
      if(outfile.df_Write((char *)buf, Bytes) != DiskFileB::df_NO_ERROR) {
	DeviceErrorHandler(outfile.df_ExceptionMessage());
      }
      break;

    case  gxDEVICE_STREAM_SOCKET: 
      if(!stream_sock) { ready_for_writing = 0; return; }
      else { ready_for_writing = 1; }
      if(stream_sock->WriteBlock((char *)buf, Bytes) != 0)
	DeviceErrorHandler(stream_sock->SocketExceptionMessage());
      break;
      
    case gxDEVICE_DATAGRAM_SOCKET:
      if(!datagram_sock) { ready_for_writing = 0; return; }
      else { ready_for_writing = 1; }
      if(datagram_sock->WriteBlock((char *)buf, Bytes) != 0)
	DeviceErrorHandler(datagram_sock->SocketExceptionMessage());
      break;

    case gxDEVICE_SERIAL_PORT: 
      if(!serial_port) { ready_for_writing = 0; return; }
      else { ready_for_writing = 1; }
      if(serial_port->WriteBlock((char *)buf, Bytes) != 0)
	DeviceErrorHandler(serial_port->SerialCommExceptionMessage());
      break;

    case gxDEVICE_NULL:
      break;
      
    default:
      break;
  }
}

int gxsFile::CopyFileToStreamSocket(gxStream *s, FAU_t &byte_count)
// Copy a disk file to a stream socket. Returns true if no errors
// occurred. NOTE: This function assumes that file has been open
// by the calling OpenInputFile/OpenOutputFile function and the
// socket has already been initialized. The calling function is
// responsible for flushing the cache buffers and closing any
// open disk files.
{
  if(!infile) return 0;
  if(!s) return 0;
  stream_sock = s;

  gxDeviceTypes o_device = gxDEVICE_STREAM_SOCKET; // Output device
  gxDeviceTypes i_device = gxDEVICE_DISK_FILE;     // Input device

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the file into the cache 
  byte_count = LoadFile(p, infile.df_Length());

  return 1;
}

int gxsFile::CopyFileToDatagramSocket(gxDatagram *s, FAU_t &byte_count) 
// Copy a disk file to a datagram socket. Returns true if no errors
// occurred. NOTE: This function assumes that file has been open
// by the calling OpenInputFile/OpenOutputFile function and the
// socket has already been initialized. The calling function is
// responsible for flushing the cache buffers and closing any
// open disk files.
{
  if(!infile) return 0;
  if(!s) return 0;
  datagram_sock = s;

  gxDeviceTypes o_device = gxDEVICE_DATAGRAM_SOCKET; // Output device
  gxDeviceTypes i_device = gxDEVICE_DISK_FILE; 

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the file into the cache 
  byte_count = LoadFile(p, infile.df_Length());

  return 1;
}

int gxsFile::CopyFileToSerialPort(gxSerialCommServer *s, FAU_t &byte_count)
// Copy a disk file to a serial port. Returns true if no errors
// occurred. NOTE: This function assumes that file has been open
// by the calling OpenInputFile/OpenOutputFile function and the
// port has already been initialized. The calling function is
// responsible for flushing the cache buffers and closing any
// open disk files.
{
  if(!outfile) return 0;
  if(!s) return 0;
  serial_port = s;

  gxDeviceTypes o_device = gxDEVICE_SERIAL_PORT; // Output device
  gxDeviceTypes i_device = gxDEVICE_DISK_FILE; 

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the file into the cache 
  byte_count = LoadFile(p, infile.df_Length());

  return 1;
}

int gxsFile::CopyFileToFile(FAU_t &byte_count)
// Copy a disk file to another disk file . Returns true if no errors
// occurred. NOTE: This function assumes that files have been open
// by the calling OpenInputFile/OpenOutputFile function. The calling
// function is responsible for flushing the cache buffers and closing
// any open disk files.

{
  if(!infile) return 0;
  if(!outfile) return 0;
  
  gxDeviceTypes o_device = gxDEVICE_DISK_FILE; // Output device
  gxDeviceTypes i_device = gxDEVICE_DISK_FILE; 

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the file into the cache 
  byte_count = LoadFile(p, infile.df_Length());
  return 1;
}

FAU_t gxsFile::LoadFile(gxDeviceCachePtr p, FAU_t end_of_file)
// Load a file from disk into the device cache. Returns the
// number bytes read from the file.
{
  FAU_t byte_count = (FAU_t)0;

  // The file is smaller then one block
  if(end_of_file <= (FAU_t)MEMORY_BLOCK_SIZE) { 
    byte_count = end_of_file;
    p.Alloc((unsigned)end_of_file); // Load the cache bucket
  }
  else { // The file is larger then one block
    while(end_of_file > (FAU_t)MEMORY_BLOCK_SIZE) {
      byte_count += MEMORY_BLOCK_SIZE;
      p.Alloc(MEMORY_BLOCK_SIZE); // Load the cache bucket
      end_of_file -= MEMORY_BLOCK_SIZE;
      if(end_of_file <= (FAU_t)MEMORY_BLOCK_SIZE) {
	byte_count += end_of_file;
	p.Alloc((unsigned)end_of_file); // Load the cache bucket
	break;
      }
      else
	continue;
    }
  }
  return  byte_count;
}

int gxsFile::OpenInputFile(const char *in)
// Open the file if it exists. Returns false
// it the file cannot be opened or if it does
// not exist.
{
  infile.df_Open(in);
  if(!infile) return 0;
  return 1;
}

int gxsFile::OpenOutputFile(const char *out)
// Open the specified file for writing and truncate
// it. Returns false if the file cannot be opened.
{
  outfile.df_Create(out);
  if(!outfile) return 0;
  return 1;
}

int gxsFile::CopyStreamSocketToFile(gxStream *s, gxBlockHeader &gxs)
{
  if(!s) return 0; 
  stream_sock = s;
  curr_stream_hdr = gxs;

  gxDeviceTypes o_device = gxDEVICE_DISK_FILE;     // Output device
  gxDeviceTypes i_device = gxDEVICE_STREAM_SOCKET; // Input device

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the cache buckets
  p.Alloc((__ULWORD__)gxs.block_length);

  return 1;
}

int gxsFile::CopyDatagramSocketToFile(gxDatagram *s, gxBlockHeader &gxs)
{
  if(!s) return 0; 
  datagram_sock = s;
  curr_datagram_hdr = gxs;

  gxDeviceTypes o_device = gxDEVICE_DISK_FILE;       // Output device
  gxDeviceTypes i_device = gxDEVICE_DATAGRAM_SOCKET; // Input device

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the cache buckets
  p.Alloc((__ULWORD__)gxs.block_length);

  return 1;
}

void gxsFile::CloseOutputFile()
{
  outfile.df_Close();
}

void gxsFile::CloseInputFile()
{
  infile.df_Close();
}

void gxsFile::Flush()
{
  cache.Flush();
}

int gxsFile::CopySerialPortToFile(gxSerialCommServer *s, gxBlockHeader &gxs)
{
  if(!outfile) return 0;
  if(!s) return 0;
  serial_port = s;
  curr_serial_hdr = gxs;

  gxDeviceTypes o_device = gxDEVICE_DISK_FILE;   // Output device
  gxDeviceTypes i_device = gxDEVICE_SERIAL_PORT; // Input device 

  // Setup a pointer to the cache buckets
  gxDeviceCachePtr p(cache, o_device, i_device); 

  // Load the cache buckets
  p.Alloc((__ULWORD__)gxs.block_length);

  return 1;
}

void gxsFile::DeviceErrorHandler(const char *mesg)
{
  // Display the device error and exit the program
  GXSTD::cout << mesg << "\n";
  exit(0);
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/socket_cache/server.cpp 555 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 "gxsfile.h"

// 10/31/2026: Stream server options, see above
static const char *opt_cert = 0, *opt_key = 0, *opt_client_ca = 0;
static const char *opt_fp[16], *opt_cn[16];
static int num_fp = 0, num_cn = 0;
static int opt_open = 0, opt_allow_shutdown = 0;

static void PrintableName(const char *s)
// Print a name from a client certificate with control characters escaped
{
  for(; s && *s; s++) {
    unsigned char c = (unsigned char)*s;
    if(c < 0x20 || c == 0x7f) cout << "?";
    else cout << (char)c;
  }
}

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

void ClearInputStream(istream &s)
{
  char c;
  s.clear();
  while(s.get(c) && c != '\n') { ; }
}

void InputString(char *mesg, MemoryBuffer &s)
{
  cout << mesg << ": ";
  char buf[255];
  for(int i = 0; i < 255; i++) buf[i] = 0;
  cin >> buf;
  s.Load(buf, (strlen(buf) + 1));
  s[s.length()] += '\0'; // Null terminate the string
}

void InputInt(char *mesg, int &i)
{
  cout << mesg << ": ";
  cin >> i;
  ClearInputStream(cin);
}

void Menu()
{
  cout << "\n" << flush;
  cout << "(?)   Display this menu" << "\n" << flush;
  cout << "(D)   Copy a Datagram Socket to a disk file" << "\n" << flush;
  cout << "(F)   Copy a disk file to another disk file" << "\n" << flush;
  cout << "(P)   Copy a Serial port to a disk file" << "\n" << flush;
  cout << "(Q)   Quit this program" << "\n" << flush;
  cout << "(S)   Copy a Stream Socket to a disk file" << "\n" << flush;
  cout << "\n" << flush;
}

int CopyStreamSocketToFile(gxsFile *dev)
// Copies data from a stream socket to the memory cache
// and flushes the cache buffers to a disk file.
{
  MemoryBuffer s;
  InputString("Enter the name of the output file", s);
  
  if(!dev->OpenOutputFile((char *)s)) {
    cout << "Could not open the " << (char *)s << " file" << "\n" << flush;
    return 0;
  }

  int port;
  InputInt("Enter the server's port number", port);

  gxStream server;
  gxsSocket_t remote_socket;
  FAU_t byte_count = (FAU_t)0;

  // 10/31/2026: Client authentication, or the explicit --open opt-out
  if(opt_cert) server.SetServerCert(opt_cert, opt_key);
  if(opt_client_ca) server.SetClientCAFile(opt_client_ca);
  for(int i = 0; i < num_fp; i++) {
    if(server.AllowClientFingerprint(opt_fp[i]) != 0) {
      cout << "Bad fingerprint: " << server.TLSError() << "\n" << flush;
      return 1;
    }
  }
  for(int i = 0; i < num_cn; i++) server.AllowClientCN(opt_cn[i]);
  if(opt_open) server.AllowAnonymousClients(true);
  
  cout << "Initializing the GX stream server..." << "\n" << flush;
  if(server.StreamServer(port) != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    if(*server.TLSError()) cout << server.TLSError() << "\n" << flush;
    return 1;
  }
  
  // Get the host name assigned to this machine
  char hostname[gxsMAX_NAME_LEN];
  if(server.HostName(hostname) != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  cout << "Opening stream server on host " << hostname << "\n" << flush;
  int server_up = 1;

  cout << "Listening on port " << port << "\n" << flush;
  remote_socket = server.Accept();
  
  if(remote_socket < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    if(*server.TLSError()) cout << server.TLSError() << "\n" << flush;
    return 1;
  }
  if(server.ClientAuthenticated()) {
    cout << "Client certificate CN=";
    PrintableName(server.PeerCN());
    cout << " SHA-256 " << server.PeerFingerprint() << "\n" << flush;
  }

  while(server_up) {
    // Read the block following a client connection
    gxBlockHeader gx;
    if(server.ReadClientHeader(gx) != 0) {
      cout << server.SocketExceptionMessage() << "\n" << flush;
      return 1;
    }

    // Get the client info
    char client_name[gxsMAX_NAME_LEN]; int r_port = -1;
    server.GetClientInfo(client_name, r_port);
    cout << client_name << " connecting on port " << r_port << "\n" << flush;
    
    // Read the status byte to determine what to do with this block
    __ULWORD__ block_status = gx.block_status;
    __SBYTE__ status = (__SBYTE__)((block_status & 0xFF00)>>8);

    switch(status) { 
      // Process each block of data
      case gxSendBlock :  
	// 10/31/2026: The length comes from the client. Check it before
	// the cache allocates a buffer for it.
	if((__ULWORD__)gx.block_length > (__ULWORD__)server.MaxBlockSize()) {
	  cout << "Block of " << gx.block_length << " bytes is too large" 
	       << "\n" << flush;
	  return 0;
	}
	cout << "Reading " << gx.block_length << " bytes from " << client_name 
	     << " remote port " << r_port << "\n" << flush;
	
	if(!dev->CopyStreamSocketToFile(&server, gx)) {
	  cout << "Error copying from stream to the file." << "\n" << flush;
	  return 0;
	}
	
	byte_count += (__ULWORD__)gx.block_length;
	break;

      case gxKillServer:
	// 10/31/2026: Any client could stop the server. Obeyed only with
	// --allow-remote-shutdown.
	if(!opt_allow_shutdown) {
	  cout << "Client shutdown request ignored" << "\n" << flush;
	  server.Close();
	  server_up = 0;
	  break;
	}
	cout << "Client shutdown the server" << "\n" << flush;
	server.Close();
	server_up = 0;
	break;

      default:
	cout << "Only accepting raw data blocks" << "\n" << flush;
	cout << "The \"" << status << "\" command was rejected" << "\n" 
	     << flush;
	server.CloseRemoteSocket();
	break;
    }
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  dev->Flush(); // Flush all the cache buffers before exiting
  dev->CloseOutputFile();
  cout << "Exiting..." << "\n" << flush;
  return 1;
}

int CopyDatagramSocketToFile(gxsFile *dev)
// Copies data from a stream socket to the memory cache
// and flushes the cache buffers to a disk file.
{
  MemoryBuffer s;
  InputString("Enter the name of the output file", s);
  
  if(!dev->OpenOutputFile((char *)s)) {
    cout << "Could not open the " << (char *)s << " file" << "\n" << flush;
    return 0;
  }

  int port;
  InputInt("Enter the server's port number", port);

  gxDatagram server;
  FAU_t byte_count = (FAU_t)0;
  
  cout << "Initializing the GX datagram server..." << "\n" << flush;
  if(server.DatagramServer(port) != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

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

  // Find out what port was really assigned 
  int assigned_port;
  if(server.PortNumber(assigned_port) != 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }
  cout << "Port assigned is " << assigned_port << "\n" << flush;

  int server_up = 1;
  while(server_up) {
    // Read the block following a client connection
    gxBlockHeader gx;
    if(server.ReadClientHeader(gx) != 0) {
      cout << server.SocketExceptionMessage() << "\n" << flush;
      return 1;
    }

    // Get the client info
    char client_name[gxsMAX_NAME_LEN]; int r_port = -1;
    server.GetClientInfo(client_name, r_port);
    cout << client_name << " connecting on port " << r_port << "\n" << flush;

    // Read the status byte to determine what to do with this block
    __ULWORD__ block_status = gx.block_status;
    __SBYTE__ status = (__SBYTE__)((block_status & 0xFF00)>>8);

    switch(status) { 
      // Process each block of data
      case gxSendBlock :
	// 11/14/2026: The length comes from the client. Check it before
	// the cache allocates a buffer for it.
	if((__ULWORD__)gx.block_length > (__ULWORD__)server.MaxBlockSize()) {
	  cout << "Block of " << gx.block_length << " bytes is too large" 
	       << "\n" << flush;
	  return 0;
	}
	cout << "Reading " << gx.block_length << " bytes from " << client_name 
	     << " remote port " << r_port << "\n" << flush;
	
	if(!dev->CopyDatagramSocketToFile(&server, gx)) {
	  cout << "Error copying from stream to the file." << "\n" << flush;
	  return 0;
	}

	byte_count += (__ULWORD__)gx.block_length;
	break;

      case gxKillServer:
	cout << "Client shutdown the server" << "\n" << flush;
	server.Close();
	server_up = 0;
	break;
	
      default:
	cout << "Only accepting raw data blocks" << "\n" << flush;
	cout << "The \"" << status << "\" command was rejected" << "\n" 
	     << flush;
	break;
    }
  }
    
  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  dev->Flush(); // Flush all the cache buffers before exiting
  dev->CloseOutputFile();
  cout << "Exiting..." << "\n" << flush;
  return 1;
}

void CopyFileToFile(gxsFile *dev)
{
  MemoryBuffer in, out;

  InputString("Enter the name of the input file", in);

  if(!dev->OpenInputFile(in)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }

  InputString("Enter the name of the output file", out);
  
  if(!dev->OpenOutputFile(out)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }

  FAU_t byte_count = (FAU_t)0;

  if(!dev->CopyFileToFile(byte_count)) {
    cout << "Error copying file." << "\n" << flush;
    return;
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseInputFile(); dev->CloseOutputFile();
  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void CopySerialPortToFile(gxsFile *dev) 
{
  MemoryBuffer out, port;
  InputString("Enter the name of the serial device", port);
  InputString("Enter the name of the output file", out);

  if(!dev->OpenOutputFile(out)) {
    cout << "Cannot open the specified file!" << "\n" << flush;
    return;
  }
  
  FAU_t byte_count = (FAU_t)0;
  gxSerialCommServer server;

  cout << "Initializing the GX serial port server..." << "\n" << flush;
  int rv = server.InitCommServer(port);
  if(rv != gxSerialComm::scomm_NO_ERROR) {
    cout << server.SerialCommExceptionMessage() << "\n" << flush;
    return;
  }
  
  cout << "Opening GX serial port server on " << (char*)port << "\n" 
       << flush;  

  int server_up = 1;
  while(server_up) {
    // Wait for a block header.
    gxBlockHeader gx;
    if(server.ReadHeader(gx) != 0) {
      cout << server.SerialCommExceptionMessage() << "\n" << flush;
      return;
    }
    
    cout << "Client connecting on " << (char *)port << "\n" << flush;
    
    // Read the status byte to determine what to do with this block
    __ULWORD__ block_status = gx.block_status;
    __SBYTE__ status = (__SBYTE__)((block_status & 0xFF00)>>8);
    
    switch(status) { 
      // Process each block of data
      case gxSendBlock :
	// 11/14/2026: The length comes from the client. Check it before
	// the cache allocates a buffer for it.
	if((__ULWORD__)gx.block_length > (__ULWORD__)gxDATAGRAM_DEF_MAX_BLOCK) {
	  cout << "Block of " << gx.block_length << " bytes is too large" 
	       << "\n" << flush;
	  return; // This function returns void
	}
	cout << "Reading database block " << gx.block_length
	     << " bytes in length" << "\n" << flush;
	if(!dev->CopySerialPortToFile(&server, gx)) {
	  cout << "Error copying from serial port to the file." << "\n" 
	       << flush;
	  return;
	}
	byte_count += (__ULWORD__)gx.block_length;
    	break;

      case gxKillServer:
	cout << "Client shutdown the server" << "\n" << flush;
	server.Close();
	server_up = 0;
	break;

      default:
	cout << "Only accepting raw data blocks" << "\n" << flush;
	cout << "The \"" << status << "\" command was rejected" << "\n" 
	     << flush;
	break;
    }
  }

  cout << "Number of cache buckets in use = " << dev->BucketsInUse() << "\n" 
       << flush;
  cout << "Flushing the device cache..." << "\n" << flush;
  dev->Flush();
  dev->CloseOutputFile();
  cout << "Finished processing file." << "\n" << flush;
  cout << "Byte count = " << (long)byte_count << "\n" << flush;
}

void SetupServer(int server_type)
{
  int cache_size = 1024;
  gxsFile dev(cache_size); // Device cache used to process a file

  cout << "Creating a device cache using " << cache_size 
       << " cache buckets." << "\n" << flush;
  cout << "Reserving " << (sizeof(gxDeviceBucket) * cache_size) 
       << " bytes of memory." << "\n" << flush;
  cout << "Number of cache buckets in use = " << dev.BucketsInUse() << "\n" 
       << flush;
  cout << "\n" << flush;
  
  switch(server_type) {
    case gxSOCKET_STREAM_SERVER:
      CopyStreamSocketToFile(&dev);
      Menu();
      break;
      
    case gxSOCKET_DATAGRAM_SERVER:
      CopyDatagramSocketToFile(&dev);
      Menu();
      break;

    case gxSOCKET_SERIAL_PORT_SERVER:
      CopySerialPortToFile(&dev);
      Menu();
      break;
      
    case gxSOCKET_LOCAL_FILE_SYSTEM:
      CopyFileToFile(&dev);
      Menu();
      break;
      
    default:
      break;
  }
}

int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  // 10/31/2026: Stream server options
  for(int i = 1; i < argc; i++) {
    if(strcmp(argv[i], "--cert") == 0 && i + 1 < argc) opt_cert = argv[++i];
    else if(strcmp(argv[i], "--key") == 0 && i + 1 < argc) opt_key = argv[++i];
    else if(strcmp(argv[i], "--client-ca") == 0 && i + 1 < argc) {
      opt_client_ca = argv[++i];
    }
    else if(strcmp(argv[i], "--allow-fingerprint") == 0 && i + 1 < argc &&
	    num_fp < 16) {
      opt_fp[num_fp++] = argv[++i];
    }
    else if(strcmp(argv[i], "--allow-cn") == 0 && i + 1 < argc && 
	    num_cn < 16) {
      opt_cn[num_cn++] = argv[++i];
    }
    else if(strcmp(argv[i], "--open") == 0) opt_open = 1;
    else if(strcmp(argv[i], "--allow-remote-shutdown") == 0) {
      opt_allow_shutdown = 1;
    }
    else {
      cout << "Usage: " << argv[0] << " [--cert server.pem --key server.key]"
	   << " [--client-ca ca.pem] [--allow-fingerprint SHA256]..."
	   << " [--allow-cn NAME]... [--open] [--allow-remote-shutdown]"
	   << "\n" << flush;
      return 1;
    }
  }
  if(opt_open && (opt_client_ca || num_fp || num_cn)) {
    cout << "--open cannot be used with --client-ca, --allow-fingerprint"
	 << " or --allow-cn" << "\n" << flush;
    return 1;
  }
  if((opt_cert == 0) != (opt_key == 0)) {
    cout << "--cert and --key go together" << "\n" << flush;
    return 1;
  }

  Menu();
  
  char key;
  int rv = 1;
  while(rv) {
    if (!cin) {
      ClearInputStream(cin);
      if (!cin) { 
	cout << "Input stream error" << "\n" << flush;
	return 0;
      }
    }
    cout << "\n" << flush;
    cout << '>';
    cin >> key;

    if (!cin) continue;
    switch(key) {
      case 'd' : case 'D' : 
	ClearInputStream(cin);
	SetupServer(gxSOCKET_DATAGRAM_SERVER);
	break;
	
      case 'f' : case 'F' : 
	ClearInputStream(cin);
	SetupServer(gxSOCKET_LOCAL_FILE_SYSTEM);
	break;
	
      case 'p' : case 'P' : 
	ClearInputStream(cin);
	SetupServer(gxSOCKET_SERIAL_PORT_SERVER);
	break;
	
      case 's' : case 'S' : 
	ClearInputStream(cin);
	SetupServer(gxSOCKET_STREAM_SERVER);
	break;

      case 'q' : case 'Q' :
	rv = 0;
	break;

      case '?' :
	Menu();
	break;

      default:
        cout << "Unrecognized command" << "\n" << flush;
	cout << "\n" << flush;
    }
  }
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/socket_cache/gxsfile.h 65 lines
#ifndef __GXS_FILE_HPP__
#define __GXS_FILE_HPP__

#include "gxdlcode.h"

#include <stdlib.h>
#include "devcache.h"
#include "membuf.h"
#include "memblock.h"
#include "gxstream.h"
#include "gxdatagm.h"
#include "scomserv.h"
#include "dfileb.h"

class gxsFile : public gxDeviceCache
{
public:
  gxsFile(int CacheSize = 1024);
  ~gxsFile() { }

public:
  void DeviceErrorHandler(const char *mesg);
  void Flush(); // Flush the cache buckets to the output device
  unsigned BucketsInUse() { return cache.BucketsInUse(); }
  void CloseOutputFile();
  void CloseInputFile();
  int OpenInputFile(const char *in);
  int OpenOutputFile(const char *out);
  FAU_t LoadFile(gxDeviceCachePtr p, FAU_t end_of_file);
  int CopyFileToFile(FAU_t &byte_count);
  int CopyFileToStreamSocket(gxStream *s, FAU_t &byte_count);
  int CopyFileToDatagramSocket(gxDatagram *s, FAU_t &byte_count);
  int CopyFileToSerialPort(gxSerialCommServer *s, FAU_t &byte_count);
  int CopyStreamSocketToFile(gxStream *s, gxBlockHeader &gxs);
  int CopyDatagramSocketToFile(gxDatagram *s, gxBlockHeader &gxs);
  int CopySerialPortToFile(gxSerialCommServer *s, gxBlockHeader &gxs);

private: // Base class interface
  void Read(void *buf, unsigned Bytes, gxDeviceTypes dev);
  void Write(const void *buf, unsigned Bytes, gxDeviceTypes dev);

private: // Device objects
  DiskFileB outfile;               // File used to output data
  DiskFileB infile;                // File used to input data
  gxStream *stream_sock;           // Stream socket (network device) 
  gxDatagram *datagram_sock;       // Datagram socket (network device)
  gxSerialCommServer *serial_port; // Serial port (RS232 device)

private: // Temporary variables used during read/write operations
  gxBlockHeader curr_stream_hdr;
  gxBlockHeader curr_datagram_hdr;
  gxBlockHeader curr_serial_hdr;

private: // Device cache
  gxDeviceBucketCache cache;

public: // Functions used to get the current device cache
  gxDeviceBucketCache *GetCache() { return &cache; }
};

#endif // __GXS_FILE_HPP__
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/socket_cache/modern.cpp 71 lines
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <future>
#include <iostream>
#include <iterator>
#include <thread>
#include <vector>

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

using namespace modern_net;
namespace fs = std::filesystem;

constexpr std::size_t bucket_size = 4096;

bool same_file(const fs::path &a, const fs::path &b)
{
  std::ifstream fa(a, std::ios::binary), fb(b, std::ios::binary);
  return std::equal(std::istreambuf_iterator<char>(fa), {}, std::istreambuf_iterator<char>(fb), {});
}

int main(int argc, char **argv)
{
  SocketLibrary lib;
  const fs::path in = argc > 1 ? fs::path(argv[1]) : fs::path(argv[0]);
  const fs::path out = "modern_socket_cache.out";

  gxSocket server;
  int port = listen_loopback(server);
  if(port < 0) return 1;
  std::promise<std::size_t> blocks_received;
  auto result = blocks_received.get_future();
  std::jthread rx([&] {
    std::size_t blocks = 0;
    if(server.Accept() >= 0) {
      std::ofstream dst(out, std::ios::binary | std::ios::trunc);
      while(auto block = block_frame::read_block(server.GetRemoteSocket(), bucket_size)) {
        if(block->empty()) break;              // End of the file
        dst.write(reinterpret_cast<const char *>(block->data()), std::streamsize(block->size()));
        blocks++;
      }
    }
    blocks_received.set_value(blocks);
  });

  gxSocket client(SOCK_STREAM, gxsPort_t(port), const_cast<char *>("127.0.0.1"));
  if(client.Connect() < 0) { std::cout << client.SocketExceptionMessage() << "\n"; return 1; }
  std::ifstream src(in, std::ios::binary);
  std::vector<std::byte> bucket(bucket_size);
  std::size_t sent = 0;
  while(src.read(reinterpret_cast<char *>(bucket.data()), std::streamsize(bucket.size())) ||
        src.gcount() > 0) {
    if(!block_frame::write_block(client.GetSocket(), std::span(bucket).first(std::size_t(src.gcount()))))
      break;
    sent++;
  }
  block_frame::write_block(client.GetSocket(), {});   // Empty block: done
  std::size_t received = result.get();
  client.Close();
  bool same = same_file(in, out);
  std::cout << "Sent " << sent << " blocks, server wrote " << received << "; files "
            << (same ? "match" : "DIFFER") << " (" << fs::file_size(in) << " bytes)\n";
  fs::remove(out);
  return same && sent == received ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/block_frame.h 72 lines
#ifndef MODERN_BLOCK_FRAME_H
#define MODERN_BLOCK_FRAME_H

#include <array>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <optional>
#include <span>
#include <vector>
#include <sys/socket.h>

namespace block_frame {

constexpr std::uint32_t magic = 0x67784231;     // "gxB1"
constexpr std::size_t header_size = 8;

constexpr std::uint32_t to_little(std::uint32_t v)
{
  if constexpr(std::endian::native == std::endian::little) return v;
  else return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v >> 8) & 0xff00) | (v >> 24);
}

inline bool write_all(int fd, std::span<const std::byte> data)
{
  while(!data.empty()) {
    ssize_t n = ::send(fd, data.data(), data.size(), MSG_NOSIGNAL);
    if(n <= 0) return false;
    data = data.subspan(std::size_t(n));
  }
  return true;
}

inline bool read_all(int fd, std::span<std::byte> data)
{
  while(!data.empty()) {
    ssize_t n = ::recv(fd, data.data(), data.size(), 0);
    if(n <= 0) return false;                    // Closed or error
    data = data.subspan(std::size_t(n));
  }
  return true;
}

inline bool write_block(int fd, std::span<const std::byte> data)
{
  if(data.size() > 0xffffffffu) return false;
  std::array<std::uint32_t, 2> hdr = {to_little(magic), to_little(std::uint32_t(data.size()))};
  return write_all(fd, std::as_bytes(std::span(hdr))) && write_all(fd, data);
}

// One block, or nothing if the header is bad, the length is over
// max_len, or the peer closes early.
inline std::optional<std::vector<std::byte>> read_block(int fd, std::size_t max_len)
{
  std::array<std::uint32_t, 2> hdr{};
  if(!read_all(fd, std::as_writable_bytes(std::span(hdr)))) return std::nullopt;
  if(to_little(hdr[0]) != magic) return std::nullopt;
  std::size_t len = to_little(hdr[1]);
  if(len > max_len) return std::nullopt;        // Checked before allocating
  std::vector<std::byte> data(len);
  if(!read_all(fd, data)) return std::nullopt;
  return data;
}

} // namespace block_frame

#endif // MODERN_BLOCK_FRAME_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- 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_socket_cache
./build-modern/socket_socket_cache

Output of the modern program

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

Sent 18 blocks, server wrote 18; files match (73224 bytes)