Created
August 3, 2020 18:38
-
-
Save Luukdegram/603a2ea72485680340215d02b344fd72 to your computer and use it in GitHub Desktop.
Creates a tcp server that clients can connect and write to. Client's messages appear in stderr.
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"); | |
const network = @import("network.zig"); | |
pub const io_mode = .evented; | |
pub fn main() anyerror!void { | |
const allocator = std.heap.page_allocator; | |
try network.init(); | |
defer network.deinit(); | |
var server = try network.Socket.create(.ipv4, .tcp); | |
defer server.close(); | |
try server.bind(.{ | |
.address = .{ .ipv4 = network.Address.IPv4.any }, | |
.port = 2501, | |
}); | |
try server.listen(); | |
std.debug.warn("listening at {}\n", .{try server.getLocalEndPoint()}); | |
while (true) { | |
std.debug.print("Waiting for connection\n", .{}); | |
const client = try allocator.create(Client); | |
client.* = Client{ | |
.conn = try server.accept(), | |
.handle_frame = async client.handle(), | |
}; | |
std.debug.print("Connected\n", .{}); | |
} | |
} | |
const Client = struct { | |
conn: network.Socket, | |
handle_frame: @Frame(Client.handle), | |
fn handle(self: *Client) !void { | |
try self.conn.writer().writeAll("server: welcome to the chat server\n"); | |
while (true) { | |
var buf: [100]u8 = undefined; | |
const amt = try self.conn.receive(&buf); | |
const msg = buf[0..amt]; | |
std.debug.print("Client wrote: {}", .{msg}); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment