zig run client.zig
Created
March 4, 2026 06:58
-
-
Save masakielastic/b500004d913f7c597cb944eb0127f2dd to your computer and use it in GitHub Desktop.
Zig 0.15.2 で TCP クライアント
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const std = @import("std"); | |
| fn stripCr(line: []const u8) []const u8 { | |
| if (line.len > 0 and line[line.len - 1] == '\r') return line[0 .. line.len - 1]; | |
| return line; | |
| } | |
| pub fn main() !void { | |
| var gpa: std.heap.DebugAllocator(.{}) = .init; | |
| defer _ = gpa.deinit(); | |
| const allocator = gpa.allocator(); | |
| const stream = try std.net.tcpConnectToHost(allocator, "localhost", 8080); | |
| defer stream.close(); | |
| const req = | |
| "GET / HTTP/1.1\r\n" ++ | |
| "Host: localhost\r\n" ++ | |
| "Connection: close\r\n" ++ | |
| "\r\n"; | |
| // --- write request --- | |
| var wbuf: [4096]u8 = undefined; | |
| var bw = stream.writer(&wbuf); | |
| try bw.interface.writeAll(req); | |
| try bw.interface.flush(); | |
| // --- read response (line-based) --- | |
| var rbuf: [4096]u8 = undefined; | |
| var br = stream.reader(&rbuf); | |
| const r = br.interface(); | |
| while (try r.takeDelimiter('\n')) |raw| { | |
| const line = stripCr(raw); | |
| std.debug.print("{s}\n", .{line}); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment