net/tcp
The net/tcp module provides low-level TCP listener and connection primitives.
Import
Section titled “Import”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 ! TcpListenerfn DialTcp(addr: str) -> str ! TcpConn
fn (l: &mut TcpListener) Accept() -> str ! TcpConnfn (l: TcpListener) Close()
fn (c: &mut TcpConn) Read(maxBytes: i32) -> str ! []bytefn (c: &mut TcpConn) ReadStr(maxBytes: i32) -> str ! strfn (c: &mut TcpConn) Write(buf: []byte) -> str ! i32fn (c: &mut TcpConn) WriteStr(data: str) -> str ! i32fn (c: TcpConn) Close()
fn (c: &mut TcpConn) SetReadTimeoutMs(ms: i32) -> str ! boolfn (c: &mut TcpConn) SetWriteTimeoutMs(ms: i32) -> str ! boolfn (c: &mut TcpConn) SetKeepAlive(enabled: bool) -> str ! boolExample: Echo Server
Section titled “Example: Echo Server”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(); }}Ownership Example
Section titled “Ownership Example”let c1 := tcp::DialTcp("127.0.0.1:8080") catch err { return; };let c2 := c1; // ownership moved to c2// c1.Close(); // ❌ use of moved valuec2.Close();