diff options
| author | Patrick Schönberger | 2026-04-20 14:12:19 +0200 |
|---|---|---|
| committer | Patrick Schönberger | 2026-04-20 14:12:19 +0200 |
| commit | 7b2c51a981d32bb256d91e53831c30db5fc6a15e (patch) | |
| tree | ffc182e07ef64389973572a675e6919636e2511b /src | |
| download | zhttpws-7b2c51a981d32bb256d91e53831c30db5fc6a15e.tar.gz zhttpws-7b2c51a981d32bb256d91e53831c30db5fc6a15e.zip | |
Initial commit
Diffstat (limited to 'src')
| -rw-r--r-- | src/main.zig | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/src/main.zig b/src/main.zig new file mode 100644 index 0000000..f06c7ff --- /dev/null +++ b/src/main.zig @@ -0,0 +1,79 @@ +const std = @import("std"); +const Io = std.Io; + +const default = @import("default"); + +fn handle_request(io: std.Io, stream: std.Io.net.Stream) !void { + var recv_buffer: [999]u8 = undefined; + var send_buffer: [100]u8 = undefined; + + defer stream.close(io); + + var connection_br = stream.reader(io, &recv_buffer); + var connection_bw = stream.writer(io, &send_buffer); + var server = std.http.Server.init(&connection_br.interface, &connection_bw.interface); + + while (true) { + var req = server.receiveHead() catch break; + + switch (req.upgradeRequested()) { + .websocket => |ws| { + std.debug.print("ws: {s}\n", .{ws.?}); + var websocket = req.respondWebSocket(.{ .key = ws.? }) catch { + std.debug.print("error responding\n", .{}); + break; + }; + std.debug.print("responded, now we wait\n", .{}); + try websocket.writeMessage("abcde", .text); + try websocket.flush(); + const sm = try websocket.readSmallMessage(); + std.debug.print("sm: {s}\n", .{sm.data}); + }, + else => {}, + } + + try req.respond( + \\ <script> + \\ const socket = new WebSocket("ws://localhost:1234"); + \\ socket.addEventListener("open", (event) => { + \\ socket.send("Hello Server!"); + \\ }); + \\ socket.addEventListener("message", (event) => { + \\ console.log("Message from server ", event.data); + \\ }); + \\ </script> + \\ <p>hallo</p> + , .{ .status = .ok }); + } + + std.debug.print("closing thread\n", .{}); +} + +pub fn main(init: std.process.Init) !void { + // Prints to stderr, unbuffered, ignoring potential errors. + std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); + + // This is appropriate for anything that lives as long as the process. + const arena: std.mem.Allocator = init.arena.allocator(); + + // Accessing command line arguments: + const args = try init.minimal.args.toSlice(arena); + for (args) |arg| { + std.log.info("arg: {s}", .{arg}); + } + + // In order to do I/O operations need an `Io` instance. + const io = init.io; + + const address = try std.Io.net.IpAddress.parseIp4("0.0.0.0", 1234); + var net_server = try address.listen(io, .{ .reuse_address = true }); + + while (true) { + const stream = try net_server.accept(io); + + const future = io.async(handle_request, .{ io, stream }); + _ = future; + + std.debug.print("creating thread\n", .{}); + } +} |
