Skip to content

Instantly share code, notes, and snippets.

@alichraghi
Created September 10, 2021 11:11
Show Gist options
  • Save alichraghi/dea5cebf7e24d5189d52d052470beb42 to your computer and use it in GitHub Desktop.
Save alichraghi/dea5cebf7e24d5189d52d052470beb42 to your computer and use it in GitHub Desktop.
Zig TCP Server
const std = @import("std");
const net = std.net;
const StreamServer = net.StreamServer;
const Options = StreamServer.Options;
const Address = net.Address;
pub fn main() anyerror!void {
const address = Address.initIp4([4]u8{ 127, 0, 0, 1 }, 8080);
var stream = StreamServer.init(Options{ .reuse_address = true });
defer stream.deinit();
try stream.listen(address);
while (true) {
const conn = try stream.accept();
defer conn.stream.close();
var buf : [4096]u8 = undefined;
_ = try conn.stream.read(buf[0..]);
const message = "HTTP/1.1 200 OK\n\nHello world!";
_ = try conn.stream.write(message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment