Skip to content

Instantly share code, notes, and snippets.

@lithdew
Created September 8, 2020 05:47
Show Gist options
  • Save lithdew/eaf4d390c671654f95ab3ad05c5a9f9b to your computer and use it in GitHub Desktop.
Save lithdew/eaf4d390c671654f95ab3ad05c5a9f9b to your computer and use it in GitHub Desktop.
zig: graceful tcp client shutdown
const std = @import("std");
const os = std.os;
const File = std.fs.File;
pub fn shutdown(fd: os.fd_t, how: i32) !void {
const rc = os.system.shutdown(fd, how);
switch (os.errno(rc)) {
0 => return,
os.EBADF => unreachable,
os.EINVAL => return error.UnknownShutdownMethod,
os.ENOTCONN => return error.SocketNotConnected,
os.ENOTSOCK => return error.FileDescriptorNotSocket,
else => unreachable,
}
}
pub fn dispose(file: File) void {
shutdown(file.handle, os.SHUT_RDWR) catch |err| switch (err) {
error.SocketNotConnected => @panic(@errorName(err)),
else => @panic(@errorName(err)),
};
// file.close();
std.event.Loop.instance.?.close(file.handle);
std.log.info("ok", .{});
}
pub fn readLoop(conn: File) !void {
var buf: [4096]u8 = undefined;
while (true) {
const n = try os.read(conn.handle, &buf);
if (n == 0) return error.EndOfStream;
}
}
pub const io_mode = .evented;
pub fn main() !void {
var conn = try std.net.tcpConnectToAddress(try std.net.Address.parseIp("127.0.0.1", 9000));
var frame = async readLoop(conn);
std.time.sleep(1000 * std.time.ns_per_ms);
dispose(conn);
try await frame;
std.log.info("done!", .{});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment