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
時,接收和傳送函式呼叫是異步的,並與標準函式庫事件循環配合。
其他呼叫(連接、監聽、接受等)被阻塞。