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() {
uint16_t port = server.getAddress().getPort();
std::thread echo([&server]() {
std::string line;
while(std::getline(peer, line)) {
peer << "echo: " << line << std::endl;
}
});
client << "hello" << std::endl;
std::string answer;
std::getline(client, answer);
std::cout << answer << std::endl;
client.shutdown();
echo.join();
return 0;
}