Skip to main content
Be Bitwise
C++Networking in C++

TCP with Classes

Stacking another layer on top of our socket wrappers gets us TcpClient and TcpServer, where the BSD-API ceremony stays out of sight.

TcpClient

cpp
class TcpClient {
Socket socket;
public:
void connect(const std::string &host, uint16_t port) {
InetAddress addr(host, port);
if (::connect(socket.get(), addr.as_sockaddr(), addr.size()) < 0) {
throw std::runtime_error("Connection failed");
}
}
void send_data(const std::string &data) {
size_t sent = 0;
while (sent < data.size()) {
// MSG_NOSIGNAL (Linux): a dead peer gives EPIPE instead of a
// SIGPIPE that kills the process. macOS uses SO_NOSIGPIPE instead.
ssize_t n = ::send(socket.get(), data.c_str() + sent,
data.size() - sent, MSG_NOSIGNAL);
if (n < 0 && errno == EINTR) continue; // interrupted: retry
if (n <= 0) throw std::runtime_error("Send failed");
sent += static_cast<size_t>(n);
}
}
// std::nullopt means the peer closed the connection; errors throw
std::optional<std::string> receive(size_t max_size = 4096) {
std::string buffer(max_size, '\0');
ssize_t n = ::recv(socket.get(), buffer.data(), buffer.size(), 0);
if (n == 0) return std::nullopt;
if (n < 0) throw std::runtime_error("Receive failed");
buffer.resize(static_cast<size_t>(n));
return buffer;
}
};

Usage

cpp
TcpClient client;
client.connect("127.0.0.1", 8080);
client.send_data("GET / HTTP/1.1\r\nHost: localhost\r\n\r\n");
if (auto response = client.receive()) {
std::cout << *response << std::endl;
} else {
std::cout << "server closed the connection" << std::endl;
}
Key Concept

Notice how send_data keeps looping until every byte has gone out. send() is allowed to deliver less than you asked for. On a blocking socket like this one, Linux normally waits until the whole message is queued, but a signal landing mid-call or a socket in non-blocking mode will hand you a short count. Always loop on partial sends.

You can watch short sends happen without a network. This program pushes 1 MB through a non-blocking socketpair(), playing the reader itself whenever the buffer fills, and counts how many send() calls came back short. The exact counts depend on the kernel's buffer sizes, so expect different numbers from run to run and machine to machine.

Try itReplace the loop with a single send() call and compare how many bytes the reader gets. Then notice the last recv() returns 0: that is end-of-stream, which receive() above reports as std::nullopt.
C++ (GCC 9.2.0)

TcpServer

cpp
class TcpServer {
Socket listen_socket;
public:
void bind_and_listen(uint16_t port, int backlog = 5) {
int opt = 1;
setsockopt(listen_socket.get(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
InetAddress addr(port);
if (::bind(listen_socket.get(), addr.as_sockaddr(), addr.size()) < 0) {
throw std::runtime_error("Bind failed");
}
if (::listen(listen_socket.get(), backlog) < 0) {
throw std::runtime_error("Listen failed");
}
}
Socket accept_client() {
sockaddr_in client_addr{};
socklen_t len = sizeof(client_addr);
int client_fd = ::accept(listen_socket.get(), (sockaddr*)&client_addr, &len);
if (client_fd < 0) throw std::runtime_error("Accept failed");
return Socket(client_fd);
}
};

The Pattern

Compare the C++ usage to raw C:

cpp
// C: create, check error, bind, check error, listen, check error...
// C++: server.bind_and_listen(8080); // one line, RAII handles cleanup

Fewer lines, no leaks. The destructor closes the socket the moment its wrapper falls out of scope.

Error Handling with Exceptions

Exceptions take the place of the return-code dance you'd find in C, and the code stays a lot easier to read:

cpp
try {
TcpClient client;
client.connect("192.168.1.1", 8080);
client.send_data("hello");
} catch (const std::runtime_error &e) {
std::cerr << "Network error: " << e.what() << std::endl;
}
// Socket is cleaned up by destructors, even after exception