summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohannes Stoelp <johannes.stoelp@gmail.com>2025-01-17 00:29:03 +0100
committerJohannes Stoelp <johannes.stoelp@gmail.com>2025-01-17 00:53:22 +0100
commit4f2a23efa8b144810b867c9c81587365e2c87d3f (patch)
tree441aee4d1a82e64d0bba4d2d4e7b7af70daa33df
parentb0159319727fd4cd15f62898b737786ae0e872a5 (diff)
downloadzig-playground-4f2a23efa8b144810b867c9c81587365e2c87d3f.tar.gz
zig-playground-4f2a23efa8b144810b867c9c81587365e2c87d3f.zip
net: simple tcp client server example
-rw-r--r--example-network/Makefile4
-rw-r--r--example-network/basic.zig41
2 files changed, 45 insertions, 0 deletions
diff --git a/example-network/Makefile b/example-network/Makefile
new file mode 100644
index 0000000..8fc8a1c
--- /dev/null
+++ b/example-network/Makefile
@@ -0,0 +1,4 @@
+s:
+ zig run basic.zig -- -s
+c:
+ zig run basic.zig
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);
+}