zig network
1.0.0
围绕 TCP 和 UDP 的小型网络抽象层。
select
/ poll
支持阻塞和非阻塞 I/Obuild.zig.zon
:
.{
. name = "appname" ,
. version = "0.0.0" ,
. dependencies = .{
. network = .{
. url = "https://github.com/MasterQ32/zig-network/archive/<COMMIT_HASH_HERE>.tar.gz" ,
. hash = "HASH_GOES_HERE" ,
},
},
}
(要获取哈希值,请删除包含.hash
行,然后编译器会告诉您放回哪一行)
build.zig
:
exe . addModule ( "network" , b . dependency ( "network" , .{}). module ( "network" ));
const network = @import ( "network" );
test "Connect to an echo server" {
try network . init ();
defer network . deinit ();
const sock = try network . connectToHost ( std . heap . page_allocator , "tcpbin.com" , 4242 , .tcp );
defer sock . close ();
const msg = "Hi from socket! n " ;
try sock . writer (). writeAll ( msg );
var buf : [ 128 ] u8 = undefined ;
std . debug . print ( "Echo: {}" , .{ buf [0 .. try sock . reader (). readAll ( buf [0 .. msg . len ])]});
}
有关如何使用异步 I/O 构建小型 TCP 服务器的更完整示例,请参阅 async.zig。
构建所有示例:
$ zig build examples
构建一个具体的例子:
$ zig build sync-examples
测试一个例子,例如。 echo
:
$ ./zig-out/bin/echo 3000
在另一个终端
$ nc localhost 3000
hello
hello
how are you
how are you
在 Windows 上,当在程序的根文件中设置io_mode = .evented
时,接收和发送函数调用是异步的,并与标准库事件循环配合。
其他调用(连接、监听、接受等)被阻塞。