DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_simple

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

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

Modern equivalent of the simple TCP client and server, in one program. The legacy pair is two programs started by hand; here the server runs in a std::jthread on 127.0.0.1 and a free port, and main() is the client, so the example runs (and is tested) by itself. The sockets stay gxSocket (the C++ standard library has no sockets). Modern parts: std::string and std::string_view buffers in place of char arrays, RAII for the socket library, a std::promise/std::future pair that hands the server's port to the client, and std::jthread, which joins itself.

Usage: modern (both ends in this process) modern server PORT modern client HOST PORT (like the legacy pair)

Legacy calls in this program

LegacyModern C++StandardNotes
Atoi(), Atol(), Atof(), atoi()std::from_chars() into std::optional<T>; std::stoi()C++17Overflow and junk are reported, not turned into 0.
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/simple/client.cpp 58 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 "gxsocket.h"

int main(int argc, char **argv)
{
  if(argc != 3) {
    cerr << "Usage: " << argv[0] << " hostname port" << "\n" << flush;
    return 1;
  }

  unsigned short port = (unsigned short) atoi(argv[2]);

  cout << "Constructing a stream client" << "\n" << flush;
  gxSocket client(SOCK_STREAM, port, argv[1]);
  if(!client) {
    cout << client.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  // Connect to the server
  if(client.Connect() < 0) {
    cout << client.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  char *test_block = "The quick brown fox jumps over the lazy dog \
0123456789\n";
  
  // Send a block of data
  cout << "Sending a block " << strlen(test_block) << " bytes long..." 
       << "\n" << flush;
  int rv = client.Send((char *)test_block, strlen(test_block));
  if(rv < 0) {
    cout << client.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  cout << "Sent " << rv << " bytes" << "\n" << flush;
  cout << "Exiting..." << "\n" << flush;
  client.Close(); // Close the socket connection
  client.ReleaseSocketLibrary();
  
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/simple/server.cpp 105 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 "gxsocket.h"

#if defined (__LINUX__)
#include <sys/signal.h>
#endif

int main(int argc, char **argv)
{
#if defined (__LINUX__)
  // NOTE: Linux will kill a process that attempts to write to a pipe 
  // with no readers. If this application may send data to a client socket 
  // that has disconnected tell the kernel to ignore the broken pipe.
  signal(SIGPIPE, SIG_IGN);
#endif

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

  unsigned short port = (unsigned short) atoi(argv[1]);

  cout << "Constructing a stream server" << "\n" << flush;
  gxSocket server(SOCK_STREAM, port);
  if(!server) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }
  
  // Get the host name assigned to this machine (statistical info only)
  char hostname[gxsMAX_NAME_LEN];
  int rv = server.GetHostName(hostname);
  if(rv < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  cout << "Opening stream server on host " << hostname << "\n" << flush;
  cout << "Listening on port " << port << "\n" << flush;

  // Bind the name to the socket
  rv = server.Bind();
  if(rv < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }
 
  // Listen for connections
  rv = server.Listen();
  if(rv < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  // Accept a connection and block execution until data is
  // received from a client connection to this port.
  rv = server.Accept();
  if(rv < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }

  // Get the client info (statistical info only)
  char client_name[gxsMAX_NAME_LEN]; int r_port = -1;
  server.GetClientInfo(client_name, r_port);
  cout << "Receiving data from " << client_name 
       << " remote port " << r_port << "\n" << flush;

  const int buf_len = 255; // Receive buffer size
  char sbuf[buf_len];
  // Block until the client sends some data
  // 10/31/2026: Leave room for the null; a full read wrote past the end
  rv = server.RawRemoteRead(sbuf, buf_len - 1); 
  if(rv < 0) {
    cout << server.SocketExceptionMessage() << "\n" << flush;
    return 1;
  }
  
  cout << "Received " << rv << " bytes" << "\n" << flush;

  // Print the buffer contents to the stdout for visual conformation
  sbuf[rv] = 0; // Null terminate the buffer
  cout << sbuf;

  cout << "Exiting..." << "\n" << flush;
  server.Close(); // Close the socket connection
  server.ReleaseSocketLibrary();
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/simple/modern.cpp 68 lines
#include <cstdlib>
#include <future>
#include <iostream>
#include <string>
#include <string_view>
#include <thread>

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

using namespace modern_net;

int run_server(gxSocket &server, std::promise<int> *ready = nullptr)
{
  if(ready) ready->set_value(bound_port(server));
  if(server.Accept() < 0) { std::cout << server.SocketExceptionMessage() << "\n"; return 1; }
  std::string buf(255, '\0');
  int rv = server.RawRemoteRead(buf.data(), int(buf.size()));
  if(rv < 0) { std::cout << server.SocketExceptionMessage() << "\n"; return 1; }
  buf.resize(std::size_t(rv));                  // No null terminator needed
  std::cout << "Server received " << rv << " bytes: " << buf;
  server.Close();
  return 0;
}

int run_client(const char *host, int port)
{
  gxSocket client(SOCK_STREAM, gxsPort_t(port), const_cast<char *>(host));
  if(!client || client.Connect() < 0) {
    std::cout << client.SocketExceptionMessage() << "\n";
    return 1;
  }
  constexpr std::string_view block = "The quick brown fox jumps over the lazy dog 0123456789\n";
  std::cout << "Sending a block " << block.size() << " bytes long...\n";
  int rv = client.Send(block.data(), int(block.size()));
  if(rv < 0) { std::cout << client.SocketExceptionMessage() << "\n"; return 1; }
  std::cout << "Sent " << rv << " bytes\n";
  client.Close();
  return 0;
}

int main(int argc, char **argv)
{
  ignore_sigpipe();
  SocketLibrary lib;
  if(!lib) return 1;
  const std::string_view mode = argc > 1 ? argv[1] : "";

  if(mode == "server" && argc == 3) {
    gxSocket server(SOCK_STREAM, gxsPort_t(std::atoi(argv[2])));
    if(!server || server.Bind() < 0 || server.Listen() < 0) return 1;
    return run_server(server);
  }
  if(mode == "client" && argc == 4) return run_client(argv[2], std::atoi(argv[3]));

  gxSocket server;
  if(listen_loopback(server) < 0) { std::cout << "Cannot listen\n"; return 1; }
  std::promise<int> ready;
  std::future<int> port = ready.get_future();
  int server_rv = 1;
  std::jthread t([&] { server_rv = run_server(server, &ready); });
  int client_rv = run_client("127.0.0.1", port.get());
  t.join();
  return client_rv || server_rv;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- 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_simple
./build-modern/socket_simple

Output of the modern program

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

Sending a block 55 bytes long...
Sent 55 bytes
Server received 55 bytes: The quick brown fox jumps over the lazy dog 0123456789