Zig: Simple tcp server code not compiled in macos

Created on 17 Oct 2019  路  2Comments  路  Source: ziglang/zig

const std = @import("std");
const Loop = std.event.Loop;
const Server = std.event.net.Server;
const File = std.fs.File;

pub fn main() anyerror!void {
    var ctx: u64 = undefined;
    var serverThread = try std.Thread.spawn(ctx, runServer);
    std.debug.warn("All your base are belong to us.\n");
}

pub fn runServer() !void {
    const MyServer = struct {
        tcp_server: Server,

        const Self = @This();
        async fn handler(tcp_server: *Server, _addr: *const std.net.Address, _socket: File) void {
            const self = @fieldParentPtr(Self, "tcp_server", tcp_server);
            var socket = _socket; // TODO https://github.com/ziglang/zig/issues/1592
            defer socket.close();
            const next_handler = errorableHandler(self, _addr, socket) catch |err| {
                std.debug.panic("unable to handle connection: {}\n", err);
            };
        }
        async fn errorableHandler(self: *Self, _addr: *const std.net.Address, _socket: File) !void {
            const addr = _addr.*; // TODO https://github.com/ziglang/zig/issues/1592
            var socket = _socket; // TODO https://github.com/ziglang/zig/issues/1592

            const stream = &socket.outStream().stream;
            try stream.print("hello from server\n");
        }
    };
    const ip4addr = std.net.parseIp4("127.0.0.1") catch unreachable;
    const addr = std.net.Address.initIp4(ip4addr, 0);

    var loop: Loop = undefined;
    try loop.initSingleThreaded(std.debug.global_allocator);
    var server = MyServer{ .tcp_server = Server.init(&loop) };
    defer server.tcp_server.deinit();
    try server.tcp_server.listen(&addr, MyServer.handler);
}

compile error:

zig/build/lib/zig/std/event/net.zig:48:69: error: container 'std.os' has no member called 'SOCK_CLOEXEC'
        const sockfd = try os.socket(os.AF_INET, os.SOCK_STREAM | os.SOCK_CLOEXEC | os.SOCK_NONBLOCK, os.PROTO_tcp);
                                                                    ^
test/src/main.zig:40:5: note: referenced here
    try server.tcp_server.listen(&addr, MyServer.handler);
os-macos standard library

Most helpful comment

Bad news: You're looking at some pre-async-await-rewrite experimental code from several release cycles ago.
Good news: It's planned to implement cross platform std lib networking code in the 0.6.0 release cycle

All 2 comments

That's easy to fix:

  • SOCK_CLOEXEC doesn't exist on osx
  • SOCK_NONBLOCK should be replaced by O_NONBLOCK on osx
  • For some unknown reason the IPPROTO_ constants have been shortened to just PROTO_ in the bits/ files for {linux,freebsd,netbsd}.

Bad news: You're looking at some pre-async-await-rewrite experimental code from several release cycles ago.
Good news: It's planned to implement cross platform std lib networking code in the 0.6.0 release cycle

Was this page helpful?
0 / 5 - 0 ratings