DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_pop3_client

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

Legacy: examples_socket/pop3_client/testprog.cpp · Modern: examples_modern/socket/pop3_client/modern.cpp

Modern equivalent of the POP3 client example. gxsPOP3Client stays; the message list is read into a std::string sized for it (no fixed char array), split into lines with std::string_view, and each line's message number and size are parsed with std::from_chars. With no arguments a scripted server on 127.0.0.1 plays the mailbox; with "SERVER USER PASSWORD" it uses a real one (POP3 over plain TCP sends the password in the clear: use it only on a test server).

Legacy calls in this program

LegacyModern C++StandardNotes
gxsHTTPClient, gxsSMTPClient, gxsPOP3Client, gxsIMAPClient, gxsFTPClient, gxsTelnetClientkeep them; std::string buffers; reply parsing with std::string_view and std::from_charsC++17

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/pop3_client/testprog.cpp 210 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 "gxspop3.h"

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

int CheckError(gxsPOP3Client *pop3)
{
  if(pop3->GetSocketError() != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    if(pop3->reply_buf[0] != 0) { // Check the reply buffer
      cout << pop3->reply_buf << flush;
    }
    pop3->Close();
    return 0;
  }
  return 1; // No errors reported
}


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

void Menu()
{
  cout << "\n";
  cout << "(c, C)    Reset connection" << "\n";
  cout << "(d, D)    Delete a message" << "\n";
  cout << "(h, H, ?) Display this menu" << "\n";
  cout << "(l, L)    List message numbers" << "\n";
  cout << "(r, R)    Retrieve a message" << "\n";
  cout << "(t, T)    Retrieve a message header" << "\n";   
  cout << "(q, Q)    Quit this program" << "\n";
  cout << "\n";
}

void Delete(gxsPOP3Client *pop3)
{
  int message_number = 1;
  cout << "Enter the message number> ";
  cin >> message_number;
  if(!cin) {
    cout << "Invalid input" << "\n";
    return;
  }

  const int sbuf_size = 8192;
  char sbuf[sbuf_size];

  if(pop3->POP3Delete(message_number, sbuf, sbuf_size) != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    return;
  }

  sbuf[pop3->BytesRead()] = 0;
  cout << sbuf << flush;
}

void List(gxsPOP3Client *pop3)
{
  const int sbuf_size = 8192;
  char sbuf[sbuf_size];
  if(pop3->POP3List(sbuf, sbuf_size) != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    sbuf[pop3->BytesRead()] = 0;
    cout << sbuf << flush;
    return;
  }
  sbuf[pop3->BytesRead()] = 0;
  cout << sbuf << flush;
}

void Reset(gxsPOP3Client *pop3)
{
  if(pop3->POP3RSet() != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    cout << pop3->reply_buf << flush;
    return;
  }
  cout << pop3->reply_buf << flush;
}

void Retrieve(gxsPOP3Client *pop3)
{
  int message_number = 1;
  cout << "Enter the message number> ";
  cin >> message_number;
  if(!cin) {
    cout << "Invalid input" << "\n";
    return;
  }

  const int sbuf_size = 8192;
  char sbuf[sbuf_size];
  if(pop3->POP3Retr(message_number, sbuf, sbuf_size) != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    return;
  }
  sbuf[pop3->BytesRead()] = 0;
  cout << sbuf << flush;
}

void Top(gxsPOP3Client *pop3)
{
  int message_number = 1;
  cout << "Enter the message number> ";
  cin >> message_number;
  if(!cin) {
    cout << "Invalid input" << "\n";
    return;
  }

  const int sbuf_size = 8192;
  char sbuf[sbuf_size];
  if(pop3->POP3Top(message_number, sbuf, sbuf_size) != gxSOCKET_NO_ERROR) {
    cout << pop3->SocketExceptionMessage() << "\n" << flush;
    sbuf[pop3->BytesRead()] = 0;
    cout << sbuf << flush;
    return;
  }
  sbuf[pop3->BytesRead()] = 0;
  cout << sbuf << flush;
}

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

  if(argc < 4) {
    cout << "Usage: " << argv[0] << " server username password" << "\n";
    cout << "server   = Your POP3 mail server" << "\n";
    cout << "username = Your POP3 account user name" << "\n";
    cout << "username = Your POP3 account password" << "\n";
    cout << "\n";
    cout << "Example: " << argv[0] 
	 << " popserver.xyz.com myname mypassword" << "\n";
    return 1;
  }
  char *server = argv[1];
  char *username = argv[2];
  char *password = argv[3];
 
  gxsPOP3Client pop3;

  cout << "Connecting to the POP3 server" << "\n";
  pop3.ConnectClient((const char *)server);
  if(!CheckError(&pop3)) return 1;
  cout << pop3.reply_buf << flush;

  pop3.POP3Login((const char *)username, (const char *)password);
  if(!CheckError(&pop3)) return 1;
  cout << pop3.reply_buf << flush;

  char key;
  Menu();
  int rv = 1;

  while(rv) {
    if (!cin) { 
      ClearInputStream(cin); 
      if (!cin) {  
	cout << "Input stream error" << "\n";
	return 0;
      }
    }
    cout << '>';
    cin >> key;
    if (!cin) continue;
    switch(key) {
      case '?' : Menu(); break;
      case 'h' : case 'H' : Menu(); break;
      case 'q' : case 'Q' : rv = 0; break;
      case 'C' : case 'c' : ClearInputStream(cin); Reset(&pop3); break;
      case 'd' : case 'D' : ClearInputStream(cin); Delete(&pop3); break;
      case 'l' : case 'L' : ClearInputStream(cin); List(&pop3); break;
      case 'r' : case 'R' : ClearInputStream(cin); Retrieve(&pop3); break;
      case 't' : case 'T' : ClearInputStream(cin); Top(&pop3); break;
      default:
        cout << "Unrecognized command" << "\n";
	break;
    }
  }

  pop3.POP3Logout();
  if(!CheckError(&pop3)) return 1;
  cout << pop3.reply_buf << flush;

  pop3.Close();
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/pop3_client/modern.cpp 58 lines
#include <charconv>
#include <iostream>
#include <string>
#include <string_view>

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

using namespace modern_net;

int main(int argc, char **argv)
{
  SocketLibrary lib;
  FakeServer fake;
  std::string server = argc > 3 ? argv[1] : "127.0.0.1";
  std::string user = argc > 3 ? argv[2] : "user", pass = argc > 3 ? argv[3] : "pass";
  int port = 110;
  if(argc <= 3) {
    fake.send("+OK fake POP3 ready\r\n").reply("+OK\r\n").reply("+OK logged in\r\n")
        .reply("+OK 3 messages\r\n1 120\r\n2 4500\r\n3 87\r\n.\r\n")
        .reply("+OK bye\r\n");
    port = fake.start();
  }
  gxsPOP3Client pop3;
  pop3.SetTimeOut(10, 0);
  if(pop3.ConnectClient(server.c_str(), port) != 0 ||
     pop3.POP3Login(user.c_str(), pass.c_str()) != 0) {
    std::cout << pop3.SocketExceptionMessage() << "\n";
    return 1;
  }
  std::string list(64 * 1024, '\0');
  if(pop3.POP3List(list.data(), int(list.size())) != 0) {
    std::cout << pop3.SocketExceptionMessage() << "\n";
    return 1;
  }
  list.resize(list.find('\0'));
  std::string_view rest = list;
  rest.remove_prefix(rest.find("\r\n") + 2);         // The +OK line
  for(std::size_t eol; (eol = rest.find("\r\n")) != std::string_view::npos;
      rest.remove_prefix(eol + 2)) {
    std::string_view line = rest.substr(0, eol);
    if(line == ".") break;
    int number = 0;
    long size = 0;
    auto [p, ec] = std::from_chars(line.data(), line.data() + line.size(), number);
    if(ec == std::errc() && p < line.data() + line.size())
      std::from_chars(p + 1, line.data() + line.size(), size);
    std::cout << "Message " << number << ": " << size << " bytes\n";
  }
  pop3.POP3Logout();
  pop3.Close();
  fake.join();
  return 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_pop3_client
./build-modern/socket_pop3_client

Output of the modern program

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

Message 1: 120 bytes
Message 2: 4500 bytes
Message 3: 87 bytes