Created
October 30, 2020 19:32
-
-
Save SpexGuy/380555269a343e420576f3182f4b0054 to your computer and use it in GitHub Desktop.
Is this correct nonblocking use?
This file contains 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"); | |
pub const raw = @import("zig-network"); | |
const heap_allocator = std.heap.c_allocator; | |
// config vars | |
pub var serverConnectionPort: u16 = 0x4d3; | |
pub var addressFamily: raw.AddressFamily = .ipv4; | |
pub var maxConnectionsPerFrame: usize = 4; | |
pub const Server = struct { | |
accept_socket: raw.Socket, | |
accept_set: raw.SocketSet, | |
pending_connections: std.ArrayList(raw.Socket), | |
pub fn start(family: raw.AddressFamily) !Server { | |
var socket = try raw.Socket.create(addressFamily, .tcp); | |
try socket.bindToPort(serverConnectionPort); | |
try socket.listen(); | |
var set = try raw.SocketSet.init(heap_allocator); | |
try set.add(socket, .{.read = true}); | |
return .{ | |
.accept_socket = socket, | |
.accept_set = set, | |
.pending_connections = std.ArrayList(raw.Socket).initCapacity(heap_allocator, maxConnectionsPerFrame), | |
}; | |
} | |
pub fn acceptConnectionsNonBlocking(self: *Server) void { | |
assert(self.pending_connections.items.len == 0); | |
self.pending_connections.ensureCapacity(maxConnectionsPerFrame) catch unreachable; | |
var connections: usize = 0; | |
while (connections < maxConnectionsPerFrame) : (connections += 1) { | |
if (self.tryAcceptSingleConnection()) |accepted| { | |
if (!accepted) break; | |
} else |err| { | |
handleAcceptError(err); | |
} | |
} | |
} | |
fn tryAcceptSingleConnection(self: *Server) !bool { | |
const available = try raw.waitForSocketEvent(&self.accept_set, 0)) | |
if (available == 0) return false; | |
const socket = try self.accept_socket.accept(); | |
pending_connections.appendAssumeCapacity(socket); | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment