Skip to content

net/tcp

The net/tcp module provides low-level TCP listener and connection primitives.

import "net/tcp";
type IpAddr struct {
.Value: str
};
type SocketAddr struct {
.Host: str,
.Port: i32
};
type TcpListener struct {
.handle: __tcp_listener,
.addr: str
};
type TcpConn struct {
.handle: __tcp_conn,
.local: str,
.remote: str
};

TcpListener and TcpConn are resource handles:

  • Non-copyable
  • Value passing/assignment moves ownership
  • Close() uses value receivers and consumes the handle
fn ListenTcp(addr: str) -> str ! TcpListener
fn DialTcp(addr: str) -> str ! TcpConn
fn (l: &mut TcpListener) Accept() -> str ! TcpConn
fn (l: TcpListener) Close()
fn (c: &mut TcpConn) Read(maxBytes: i32) -> str ! []byte
fn (c: &mut TcpConn) ReadStr(maxBytes: i32) -> str ! str
fn (c: &mut TcpConn) Write(buf: []byte) -> str ! i32
fn (c: &mut TcpConn) WriteStr(data: str) -> str ! i32
fn (c: TcpConn) Close()
fn (c: &mut TcpConn) SetReadTimeoutMs(ms: i32) -> str ! bool
fn (c: &mut TcpConn) SetWriteTimeoutMs(ms: i32) -> str ! bool
fn (c: &mut TcpConn) SetKeepAlive(enabled: bool) -> str ! bool
import "net/tcp";
import "std/io";
fn handle(conn: &mut tcp::TcpConn) {
let data := conn.Read(1024) catch err {
io::Println("read error:", err);
return;
};
conn.Write(data) catch err {
io::Println("write error:", err);
};
}
fn main() {
let listener := tcp::ListenTcp("127.0.0.1:8080") catch err {
io::Println("listen error:", err);
return;
};
while true {
let conn := listener.Accept() catch err {
io::Println("accept error:", err);
continue;
};
handle(&mut conn);
conn.Close();
}
}
let c1 := tcp::DialTcp("127.0.0.1:8080") catch err { return; };
let c2 := c1; // ownership moved to c2
// c1.Close(); // ❌ use of moved value
c2.Close();