TCP (Transmission Control Protocol) provides reliable, ordered byte-stream communication between hosts. It maintains connections between machines and deals with lost IP packets. HTTP adds web semantics on top of TCP; IP provides the lower-level foundation. section 4.2.1
A TCP server asks the operating system to listen on an address and port, accepts connections, then reads from and responds to clients. Ports distinguish traffic intended for different programs. The operating system supplies the TCP layer, while Zig’s std.Io wraps system calls in cross-platform abstractions. section 4.2.1 section 4.2.2
For local development, listen on 127.0.0.1: the loopback device is accessible only from your computer. Listening on 0.0.0.0 instead allows traffic through any network interface. TCP connections can then be treated much like other readers and writers. section 4.2.2 section 4.4
A local echo server
A Zig server listens on 127.0.0.1:8000, accepts a connection, and reads newline-delimited input. Connect with `ncat 127.0.0.1 8000`; sending `hello` gets `you said: hello` back. The server logs accept or read errors and continues serving. section 4.2.2
Listing 4.12 TCP echo server
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const addr = try std.Io.net.IpAddress.parse( #1
"127.0.0.1",
8000,
);
var tcp_server = try addr.listen(io, .{ #2
.reuse_address = true, #3
});
defer tcp_server.deinit(io);
serve: while (true) {
const stream = tcp_server.accept(io) catch |e| { #4
std.log.err("accept: {}", .{e}); #5
continue :serve;
};
defer stream.close(io);
while (true) {
var reader_buf: [1024]u8 = undefined;
var stream_reader = stream.reader(io, &reader_buf);
const reader = &stream_reader.interface;
const msg = reader.takeDelimiter('\n') catch |e| {
std.log.err("read: {}", .{e});
continue :serve;
} orelse &.{};
var writer_buf: [1024]u8 = undefined;
var stream_writer = stream.writer(io, &writer_buf);
const writer = &stream_writer.interface;
writer.print("you said: {s}\n", .{msg}) catch |e| {
std.log.err("write: {}", .{e});
continue :serve;
};
writer.flush() catch |e| {
std.log.err("flush: {}", .{e});
continue :serve;
};
}
}
}
Inspect the server’s address parsing, listener setup, connection handling, and buffered reads. section 4.2.2





