// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A demonstration server, which exists to be read as much as to be run. //! //! One handler serves WebSocket over HTTP/1.1 and over HTTP/2 without knowing //! which it is doing, which is the claim this library is here to make good. //! //! ```console //! $ zig build run -- --port 8080 //! $ python3 -c " //! import asyncio, websockets //! async def main(): //! async with websockets.connect('ws://127.0.0.1:8080/echo') as ws: //! await ws.send('hello') //! print(await ws.recv()) //! asyncio.run(main())" //! ``` const std = @import("std"); const Io = std.Io; const net = Io.net; const http = @import("http"); const http_io = @import("http_io"); const Request = http.server.Request; const Response = http.server.Response; const ws = @import("websocket"); const wss = @import("websocket_server"); const usage = \\usage: zig-websocket [--address A] [--port N] \\ \\ --address A The address to bind to (default 127.0.0.1). Note that \\ 0.0.0.0 is every IPv4 address and no IPv6 one, so a \\ client that resolves the host to an AAAA record will be \\ refused. On Linux, :: is usually both families at once. \\ --port N The port to bind to, or 0 to let the kernel choose \\ (default 8080) \\ ; pub fn main(init: std.process.Init) !void { const gpa = init.gpa; var address_text: []const u8 = "127.0.0.1"; var port: u16 = 8080; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "--address")) { address_text = args.next() orelse return fail("--address wants an address"); } else if (std.mem.eql(u8, arg, "--port")) { const text = args.next() orelse return fail("--port wants a number"); port = std.fmt.parseInt(u16, text, 10) catch return fail("--port wants a number"); } else { std.debug.print("{s}", .{usage}); std.process.exit(2); } } const address = net.IpAddress.parse(address_text, port) catch return fail("that is not an address"); // Threaded, because a connection blocks on its socket and the point of // the accept loop is that the next one does not wait for it. A WebSocket // connection blocks for a very long time, which makes this more true // here than it is for an ordinary HTTP server. var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io(); var listener = try http_io.tcp.Listener.listen(io, address, .{}); defer listener.deinit(io); var counter: Counter = .{}; var server: http.server.Server = .init( io, gpa, listener.listener(), .init(&counter, Counter.serve), .{}, ); std.debug.print("listening on http://{f}/\n", .{listener.localAddress()}); try server.serve(); } fn fail(message: []const u8) noreturn { std.debug.print("zig-websocket: {s}\n\n{s}", .{ message, usage }); std.process.exit(2); } /// The handler, with one piece of state so that there is something to show /// that a handler may have some. /// /// Atomic because a handler is shared: every connection is a task, and under /// HTTP/2 every *stream* is, so two requests really can be inside this at the /// same moment. const Counter = struct { open: std.atomic.Value(usize) = .init(0), total: std.atomic.Value(usize) = .init(0), fn serve(c: *Counter, req: *Request, res: *Response) anyerror!void { if (std.mem.eql(u8, req.target.path, "/")) return c.index(req, res); if (std.mem.eql(u8, req.target.path, "/echo")) return c.echo(req, res); if (std.mem.eql(u8, req.target.path, "/chat")) return c.chat(req, res); if (std.mem.eql(u8, req.target.path, "/count")) return c.count(req, res); res.status = .not_found; try res.setHeader("Content-Type", "text/plain; charset=utf-8"); try res.sendPrint("no such thing as {s}\n", .{req.target.path}); } fn index(c: *Counter, req: *Request, res: *Response) anyerror!void { _ = .{ c, req }; try res.setHeader("Content-Type", "text/plain; charset=utf-8"); try res.send( \\zig-websocket \\ \\ GET / this \\ WS /echo says back whatever you send it \\ WS /chat the same, with a subprotocol negotiated \\ GET /count how many connections this process has served \\ ); } fn count(c: *Counter, req: *Request, res: *Response) anyerror!void { _ = req; try res.setHeader("Content-Type", "text/plain; charset=utf-8"); try res.sendPrint("{d} open, {d} total\n", .{ c.open.load(.monotonic), c.total.load(.monotonic), }); } /// The whole of a WebSocket echo server. /// /// Note what is *not* here: no check of which HTTP version this arrived /// over, and no handshake arithmetic. Over HTTP/1.1 `accept` answered a /// `Sec-WebSocket-Key`; over HTTP/2 it did not, because RFC 8441 replaced /// that exchange with a pseudo-header. Neither fact reaches this far. fn echo(c: *Counter, req: *Request, res: *Response) anyerror!void { // The buffer is the largest message this connection will accept, and // it is on the stack of the task serving that one connection, so the // memory a thousand idle clients cost is a number chosen here. var buffer: [64 * 1024]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer }) catch |err| { return wss.refuse(res, err); }; _ = c.open.fetchAdd(1, .monotonic); _ = c.total.fetchAdd(1, .monotonic); defer _ = c.open.fetchSub(1, .monotonic); while (try conn.receive()) |message| { try conn.send(message.kind, message.data); } } /// The same, with a subprotocol, which is the other half of the opening /// handshake a real application uses. fn chat(c: *Counter, req: *Request, res: *Response) anyerror!void { var buffer: [64 * 1024]u8 = undefined; var conn = wss.accept(req, res, .{ .buffer = &buffer, // Most preferred first. A client that offers neither is answered // without a subprotocol, which RFC 6455 §4.2.2 allows and every // client must cope with. .subprotocols = &.{ "chat.v2", "chat.v1" }, }) catch |err| return wss.refuse(res, err); _ = c.open.fetchAdd(1, .monotonic); _ = c.total.fetchAdd(1, .monotonic); defer _ = c.open.fetchSub(1, .monotonic); while (try conn.receive()) |message| { switch (message.kind) { .text => try conn.sendText(message.data), // Something that only speaks text says so with 1003 rather // than by quietly dropping it. .binary => { try conn.close(.unsupported_data, "this endpoint speaks text"); // Keep reading until the peer's own Close arrives, which // is what finishes the handshake of §7.1.2. while (try conn.receive()) |_| {} }, } } } }; test { std.testing.refAllDecls(@This()); }