liveBook · Manning

Echo server

As explained in Systems Programming with Zig

The echo server is the book's example server program that returns processed request text to clients.

An echo server reads text from a network stream, processes it, and sends a response. It follows the REPL’s read-process-respond loop, but over a network connection. 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;
            };
        }
    }
}

The TCP implementation listens on loopback address 127.0.0.1, accepts connections, and reads and echoes lines. section 4.2.2

An HTTP version expects a POST request with text in its body. It returns the processed text with a 200 response, rejects other methods with 400, and uses error handling to respond with 500 when processing fails. section 4.2.4

Listing 4.13 Echo but web worthy
const std = @import("std");

fn handleConnection(io: std.Io, stream: std.Io.net.Stream) !void {
    var stream_reader_buf: [1024]u8 = undefined;
    var stream_writer_buf: [1024]u8 = undefined;
    var stream_reader = stream.reader(io, &stream_reader_buf);
    var stream_writer = stream.writer(io, &stream_writer_buf);

    var http_server = std.http.Server.init( #1
        &stream_reader.interface,
        &stream_writer.interface,
    );

    var request = try http_server.receiveHead(); #2
    if (request.head.method != .POST) { #3
        request.respond("", .{ .status = .bad_request }) catch {};
        return error.BadRequest;
    }

    errdefer request.respond("", .{ #4
        .status = .internal_server_error,
    }) catch {};

    var reader_buf: [1024]u8 = undefined;
    const reader =
        try request.readerExpectContinue(&reader_buf); #5

    const text = try reader.takeDelimiterExclusive(0); #6

    var body_writer_buf: [1024]u8 = undefined;
    var body_writer = try request.respondStreaming(&body_writer_buf, .{});
    const body = &body_writer.writer; #7

    try body.print("You said: {s}\n", .{text});
    try body.flush();

    try body_writer.end(); #8
}

pub fn main(init: std.process.Init) !void {
    const io = init.io;

    const addr = try std.Io.net.IpAddress.parse(
        "127.0.0.1",
        8000,
    );
    var tcp_server = try addr.listen(io, .{ .reuse_address = true });
    defer tcp_server.deinit(io);

    serve: while (true) {
        const stream = tcp_server.accept(io) catch |e| {
            std.log.err("accept: {}", .{e});
            continue :serve;
        };
        defer stream.close(io);

        handleConnection(io, stream) catch |e| { #9
            std.log.err("handleConnection: {}", .{e});
        };
    }
}

The listing shows the HTTP request handling and response path. section 4.2.4

Test the TCP server by chatting with it through ncat. For HTTP, curl can send a POST, try a GET that produces 400, or send an oversized body that produces 500; the server logs errors and keeps running. section 4.2.2 section 4.2.4

How Systems Programming with Zig covers it

How deep it goes
Builds from line-oriented TCP reads to HTTP request parsing, status responses, and logged error handling.
Examples
Uses ncat for TCP chat and curl to test successful POSTs, rejected GETs, and oversized requests.
What it assumes
Assumes foundational networking knowledge and relates network streams to file-like reading and writing of bytes.
What you can do after
Builds a small TCP echo server with Zig, then handles HTTP POST requests and tests responses with ncat and curl.
How it connects
Links network streams with REPL-style input and output, TCP, HTTP, and error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.