DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_echo_server

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

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

Modern equivalent of the TCP echo client and server. The server runs in a std::jthread and echoes every block back until the client closes; it waits for data with a select() timeout and checks its std::stop_token, so it can be stopped without canceling the thread (the legacy server loops forever in a blocking read). The client sends lines from a std::vector<std::string> and checks each echo.

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/echo_server/client.cpp 79 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 < 2) || (argc > 3)) {
    cerr << "Usage: " << argv[0] << " server [port]" << "\n";
    return 1;
  }

  char *server_ip = argv[1];
  unsigned short port = 7;
  if(argc == 3) port = (unsigned short)atoi(argv[2]);

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

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

  char *echo_string = "The quick brown fox jumps over the lazy dog \
0123456789\n";
  int echo_string_len = strlen(echo_string);

  // Send the string to the server
  cout << "Sending a string to the echo server..." << "\n";
  int rv = client.Send((char *)echo_string, echo_string_len);
  if(rv < 0) {
    cout << client.SocketExceptionMessage() << "\n";
    return 1;
  }
  cout << "Sent " << rv << " bytes" << "\n";

  char echo_buffer[255];
  int bytes_read = 0; // Total bytes read
  
  // Read the bytes sent back from the server
  while(bytes_read < echo_string_len) {
    // Block until the server sends some data
    // 10/31/2026: Leave room for the null (a full read wrote past the
    // end) and stop when the server closes (rv 0 looped for ever)
    rv = client.RawRead((char *)echo_buffer, sizeof(echo_buffer) - 1);
    if(rv <= 0) {
      if(rv < 0) cout << client.SocketExceptionMessage() << "\n";
      break;
    }
    bytes_read += rv;
    echo_buffer[rv] = 0; // Null terminate the string
    cout << echo_buffer;
  }
  cout << "Received " << bytes_read << " bytes" << "\n";

  cout << "Exiting..." << "\n";
  client.Close(); // Close the socket connection
  client.ReleaseSocketLibrary();
  
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/echo_server/server.cpp 122 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 HandleClientRequest(gxSocket *server)
// Function used to handle the client's request.
// Returns a non-zero value if an error occurs.
{
  // Record the client socket assigned by the kernel
  gxsSocket_t client_sock = server->GetRemoteSocket();

  const int buf_len = 255; // Receive buffer size
  char echo_buffer[buf_len];

  // Block until the client sends some data
  int bytes_read = server->RawRead(client_sock, echo_buffer, buf_len);
  if(bytes_read < 0) {
    cout << server->SocketExceptionMessage() << "\n" << flush;
    return -1;
  }

  while(bytes_read > 0) {
    // Echo the message back to the client
    if(server->RawWrite(client_sock, echo_buffer, bytes_read) < 0) {
      cout << server->SocketExceptionMessage() << "\n" << flush;
      return -1;
    }
    
    // Keep receiving data from the client
    bytes_read = server->RawRead(client_sock, echo_buffer, buf_len);
    if(bytes_read < 0) {
      cout << server->SocketExceptionMessage() << "\n" << flush;
      return -1;
    }
  }
  
  server->Close(client_sock);
  return 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;
  }

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

  cout << "Constructing an echo 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 echo server on host " << hostname << "\n" << flush;
  cout << "Listening on port " << port << "\n" << flush;
  cout << "Press Ctrl-C to exit" << "\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;
  }

  int server_loop = 1; 
  while(server_loop) { // Loop forever accepting connections

    // 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;
      break;
    }
    
    // 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;
    
    // Handle the clients request
    HandleClientRequest(&server);    
  }
  
  cout << "Exiting..." << "\n" << flush;
  server.Close(); // Close the socket connection
  server.ReleaseSocketLibrary();
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/echo_server/modern.cpp 56 lines
#include <iostream>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>

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

using namespace modern_net;

void echo_server(std::stop_token st, gxSocket &server)
{
  while(!st.stop_requested()) {                 // Accept, with a timeout
    if(server.ReadSelect(server.GetSocket(), 0, 100000) <= 0) continue;
    if(server.Accept() < 0) return;
    std::string buf(1024, '\0');
    while(!st.stop_requested()) {
      if(server.ReadSelect(server.GetRemoteSocket(), 0, 100000) <= 0) continue;
      int n = server.RawRemoteRead(buf.data(), int(buf.size()));
      if(n <= 0) break;                         // Client closed
      server.RemoteSend(buf.data(), n);         // Echo it back
    }
    server.CloseRemoteSocket();
  }
}

int main()
{
  ignore_sigpipe();
  SocketLibrary lib;
  gxSocket server;
  int port = listen_loopback(server);
  if(!lib || port < 0) { std::cout << "Cannot start the server\n"; return 1; }
  std::jthread t(echo_server, std::ref(server));  // Stops and joins itself

  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; }
  const std::vector<std::string> lines = {"hello\n", "The quick brown fox\n", "0123456789\n"};
  int errors = 0;
  for(const auto &line : lines) {
    client.Send(line.data(), int(line.size()));
    std::string back(line.size(), '\0');
    int n = client.Recv(back.data(), int(back.size()), 5, 0); // 5 s timeout
    back.resize(n > 0 ? std::size_t(n) : 0);
    std::cout << "Echo: " << back;
    if(back != line) errors++;
  }
  client.Close();
  t.request_stop();
  std::cout << (errors ? "Echo mismatch\n" : "All echoes matched\n");
  return errors ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H
#define MODERN_NET_H

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

#include "gxsocket.h"

namespace modern_net {

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

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

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

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

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

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

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

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

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

} // namespace modern_net

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

Build and run

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

Output of the modern program

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

Echo: hello
Echo: The quick brown fox
Echo: 0123456789
All echoes matched