Examples › Socket Examples
socket_tcp_send_file
C++20 or laterDataReel 6.4.3Portable C++ (tested on Linux)
Legacy: examples_socket/tcp_send_file/tcp_send_file.cpp · Modern: examples_modern/socket/tcp_send_file/modern.cpp
Modern equivalent of tcp_send_file: send a file over a TCP stream. The file is read with std::ifstream into a std::vector<char> buffer (no memset, no null terminator, no special case for the last block), the size comes from std::filesystem::file_size, and a receiver std::jthread on 127.0.0.1 counts the bytes so the program checks itself.
Usage: modern [FILE] (default: this program's own executable) modern HOST PORT FILE (send to a server, like the legacy program)
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| strcpy(), strncpy(), memmove() into char arrays | std::string; std::array<char, N> + string_view::copy() | C++11 / C++17 | |
| DiskFileB | std::fstream (read, write, seekg/seekp, tellg) | C++98 | |
| gxSocket | keep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeouts | C++20 | Stopping is a request, not a canceled thread blocked in accept(). |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/tcp_send_file/tcp_send_file.cpp 111 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" #include "dfileb.h" #include "futils.h" #include "gxstring.h" int main(int argc, char **argv) { if(argc != 4) { cerr << "Usage: " << argv[0] << " hostname port filename" << "\n" << flush; return 1; } DiskFileB ifile; unsigned short port = (unsigned short) atoi(argv[2]); ifile.df_Open(argv[3]); if(!ifile) { cout << "ERROR - Cannot open file " << argv[3] << "\n"; cout << ifile.df_ExceptionMessage() << "\n"; return 1; } 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; } int error_flag = 0; const unsigned read_size = 1024; const unsigned buf_size = read_size * 2; char rbuf[buf_size]; unsigned bytes_read = 0; int bytes_sent = 0; unsigned total_bytes_sent = 0; unsigned total_bytes_read = 0; while(!ifile.df_EOF()) { memset(rbuf, 0, buf_size); ifile.df_Read(rbuf, read_size); if(ifile.df_GetError() != DiskFileB::df_NO_ERROR) { if(ifile.df_GetError() == DiskFileB::df_EOF_ERROR) { bytes_read = ifile.df_BytesRead(); rbuf[bytes_read] = 0; bytes_sent = client.Send(rbuf, bytes_read); if(bytes_sent < 0) { cout << "ERROR - Socket send error" << "\n" << flush; cout << client.SocketExceptionMessage() << "\n" << flush; error_flag = 1; break; } total_bytes_sent += bytes_sent; total_bytes_read += bytes_read; error_flag = 0; break; } cout << "ERROR - A fatal I/O error reading input file" << "\n"; cout << ifile.df_ExceptionMessage() << "\n"; error_flag = 1; break; } bytes_read = ifile.df_BytesRead(); bytes_sent = client.Send(rbuf, bytes_read); if(bytes_sent < 0) { cout << "ERROR - Socket send error" << "\n" << flush; cout << client.SocketExceptionMessage() << "\n" << flush; error_flag = 1; break; } total_bytes_sent += bytes_sent; total_bytes_read += bytes_read; } cout << "Read " << total_bytes_read << " bytes" << "\n" << flush; cout << "Sent " << total_bytes_sent << " bytes" << "\n" << flush; if (error_flag != 0) { cout << "Exiting with errors" << "\n" << flush; } else { cout << "Exiting" << "\n" << flush; } client.Close(); // Close the socket connection client.ReleaseSocketLibrary(); return error_flag; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/tcp_send_file/modern.cpp 67 lines
#include <cstdlib> #include <filesystem> #include <fstream> #include <future> #include <iostream> #include <thread> #include <vector> #include "../common/modern_net.h" using namespace modern_net; namespace fs = std::filesystem; // Sends the whole file; returns the bytes sent or -1 long long send_file(gxSocket &client, const fs::path &file) { std::ifstream in(file, std::ios::binary); if(!in) return -1; std::vector<char> buf(64 * 1024); long long total = 0; while(in.read(buf.data(), std::streamsize(buf.size())) || in.gcount() > 0) { int n = int(in.gcount()); if(client.Send(buf.data(), n) != n) return -1; // Send() sends it all total += n; } return total; } int main(int argc, char **argv) { ignore_sigpipe(); SocketLibrary lib; if(argc == 4) { gxSocket client(SOCK_STREAM, gxsPort_t(std::atoi(argv[2])), argv[1]); if(client.Connect() < 0) { std::cout << client.SocketExceptionMessage() << "\n"; return 1; } long long sent = send_file(client, argv[3]); std::cout << "Sent " << sent << " bytes\n"; return sent < 0; } const fs::path file = argc > 1 ? fs::path(argv[1]) : fs::path(argv[0]); gxSocket server; int port = listen_loopback(server); std::promise<long long> received; auto result = received.get_future(); std::jthread rx([&] { long long total = 0; if(server.Accept() >= 0) { std::vector<char> buf(64 * 1024); for(int n; (n = server.RawRemoteRead(buf.data(), int(buf.size()))) > 0;) total += n; } received.set_value(total); }); 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; } long long sent = send_file(client, file); client.Close(); // End of the stream long long got = result.get(); std::cout << "File " << file.filename().string() << ": " << fs::file_size(file) << " bytes, sent " << sent << ", received " << got << "\n"; return (sent == got && got == (long long)fs::file_size(file)) ? 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_tcp_send_file ./build-modern/socket_tcp_send_file
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
File socket_tcp_send_file: 69104 bytes, sent 69104, received 69104