forum
forum copied to clipboard
【Zig 日报】监听未使用的 TCP 端口
在本例中,端口会显示在控制台中,程序会一直监听,直到有请求提出。 当端口设置为 0 时,Ip4Address 会随机分配一个端口。
//! Start a TCP server at an unused port.
//!
//! Test with
//! echo "hello zig" | nc localhost <port>
const std = @import("std");
const net = std.net;
const print = std.debug.print;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const loopback = try net.Ip4Address.parse("127.0.0.1", 0);
const localhost = net.Address{ .in = loopback };
var server = try localhost.listen(.{
.reuse_port = true,
});
defer server.deinit();
const addr = server.listen_address;
print("Listening on {}, access this port to end the program\n", .{addr.getPort()});
var client = try server.accept();
defer client.stream.close();
print("Connection received! {} is sending data.\n", .{client.address});
const message = try client.stream.reader().readAllAlloc(allocator, 1024);
defer allocator.free(message);
print("{} says {s}\n", .{ client.address, message });
}
启动时,请尝试进行如下测试:
echo "hello zig" | nc localhost <port>
默认情况下,程序以 IPv4 方式监听。 | nc localhost ::1 代替 127.0.0.1,将 net.Ip4Address.parse 替换为 net.Ip6Address.parse,并将 net.Address 创建中的 .in 字段替换为 .in6。
加入我们
Zig 中文社区是一个开放的组织,我们致力于推广 Zig 在中文群体中的使用,有多种方式可以参与进来: