UDP 回显
与 TCP 服务器示例类似,此程序将侦听指定的 IP 地址和端口,但这次是侦听 UDP 数据报。如果接收到数据,它将被回显到发送者的地址。
尽管 std.Io.net 主要侧重于 TCP 的抽象(目前为止),我们仍然可以利用套接字编程通过 UDP 进行通信。
//! Start a UDP echo on an unused port.
//!
//! Test with
//! echo "hello zig" | nc -u localhost <port>
const std = @import("std");
const net = std.Io.net;
const print = std.debug.print;
pub fn main(init: std.process.Init) !void {
const io = init.io;
// adjust the ip/port here as needed
const addr = try net.IpAddress.parse("127.0.0.1", 32100);
// Bind a UDP socket
const sock = try addr.bind(io, .{ .mode = .dgram, .protocol = .udp });
defer sock.close(io);
var buf: [1024]u8 = undefined;
print("Listen on {f}\n", .{addr});
// we did not set the NONBLOCK flag, so the program will wait until data is received
const msg = try sock.receive(io, &buf);
print(
"received {d} byte(s) from {f};\n string: {s}\n",
.{ msg.data.len, msg.from, msg.data },
);
try sock.send(io, &msg.from, msg.data);
print("echoed {d} byte(s) back\n", .{msg.data.len});
}
启动程序后,使用 nc 进行如下测试,使用 -u 标志表示 UDP:
echo "hello zig" | nc -u localhost <port>