summaryrefslogtreecommitdiff
path: root/example-network/basic.zig
diff options
context:
space:
mode:
Diffstat (limited to 'example-network/basic.zig')
-rw-r--r--example-network/basic.zig41
1 files changed, 41 insertions, 0 deletions
diff --git a/example-network/basic.zig b/example-network/basic.zig
new file mode 100644
index 0000000..967b082
--- /dev/null
+++ b/example-network/basic.zig
@@ -0,0 +1,41 @@
+const std = @import("std");
+
+fn run_server(addr: std.net.Address) !void {
+ std.debug.print("server listen on {}\n", .{addr});
+
+ var server = try addr.listen(.{ .reuse_address = true });
+ defer server.deinit();
+
+ const client = try server.accept();
+ defer client.stream.close();
+
+ try client.stream.writeAll("hello from server\n");
+
+ var msg: [16]u8 = undefined;
+ const cnt = try client.stream.readAll(&msg);
+ std.debug.print("read bytes={} msg={s}\n", .{ cnt, msg[0..cnt] });
+}
+
+fn run_client(addr: std.net.Address) !void {
+ std.debug.print("client connect to {}\n", .{addr});
+
+ const conn = try std.net.tcpConnectToAddress(addr);
+
+ try conn.writeAll("hello to server\n");
+
+ var msg: [16]u8 = undefined;
+ const cnt = try conn.readAll(&msg);
+ std.debug.print("read bytes={} msg={s}\n", .{ cnt, msg[0..cnt] });
+}
+
+pub fn main() !void {
+ var args = std.process.args();
+ const is_server = while (args.next()) |arg| {
+ if (std.mem.eql(u8, arg, "-s")) {
+ break true;
+ }
+ } else false;
+
+ const addr = std.net.Address.initIp4(.{ 127, 0, 0, 1 }, 8080);
+ if (is_server) try run_server(addr) else try run_client(addr);
+}