AnCH Framework 0.2
Another C++ Hack: C++23 utility libraries
Loading...
Searching...
No Matches
AnCH network library documentation

Introduction

AnCH network library provides TCP and UDP sockets, IPv4 and IPv6, with C++ streams for TCP.

Prerequisites

anch-cutils: streams over sockets.

Installation

CMake target anch::network:

find_package(Anch REQUIRED)
target_link_libraries(my-app PRIVATE anch::network)

See installation.

Usage

  • TcpStream is a connected TCP socket and a std::iostream : use << , >> , std::getline , ... shutdown half-closes the connection (end of transmission).
  • TcpServer listens on an address (port 0 for a free port) and accepts connections as TcpStream.
  • UdpSocket sends and receives datagrams.
  • Socket is the RAII socket descriptor ; errors are IOException (a std::system_error with errno ).

SIGPIPE is never raised: writing on a closed connection raises an exception (or sets the stream bad bit).

Example

Echo server and client:

#include "network/tcpServer.hpp"
#include "network/tcpStream.hpp"
#include <iostream>
#include <string>
#include <thread>
int
main() {
anch::network::TcpServer server("127.0.0.1", 0); // port 0: free port
uint16_t port = server.getAddress().getPort();
std::thread echo([&server]() {
anch::network::TcpStream peer = server.accept(); // TcpStream is a std::iostream
std::string line;
while(std::getline(peer, line)) {
peer << "echo: " << line << std::endl;
}
});
anch::network::TcpStream client("127.0.0.1", port);
client << "hello" << std::endl;
std::string answer;
std::getline(client, answer);
std::cout << answer << std::endl;
client.shutdown(); // end of transmission: server loop ends
echo.join();
return 0;
}