blob: 967b0826c32090d1b2560e365bd0a66e2cf36449 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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);
}
|