Skip to content

Instantly share code, notes, and snippets.

@masakielastic
Created March 4, 2026 06:58
Show Gist options
  • Select an option

  • Save masakielastic/b500004d913f7c597cb944eb0127f2dd to your computer and use it in GitHub Desktop.

Select an option

Save masakielastic/b500004d913f7c597cb944eb0127f2dd to your computer and use it in GitHub Desktop.
Zig 0.15.2 で TCP クライアント

Zig 0.15.2 で TCP クライアント

zig run client.zig
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