Module std::net

TCP networking.

Create TCP servers and clients for bidirectional byte-stream communication. Handle types (Listener, Connection) provide type-safe wrappers over raw file descriptors.

Error Handling

fs.IoError is the stable user-facing error enum for all I/O failures, including TCP network errors. Use the try_* wrappers with Result<T, fs.IoError> and the ? operator for structured error propagation:

import std::fs;

fn dial(addr: string) -> Result<Connection, fs.IoError> {
    net.try_connect(addr)
}

fn main() {
    match dial("localhost:9000") {
        Ok(conn) => println("connected"),
        Err(e) => {
            match e {
                IoError::ConnectionRefused(_) => println("nobody home"),
                IoError::TimedOut(_)          => println("timed out"),
                _                             => println("network error"),
            }
        },
    }
}

Examples

import std::net;

fn main() {
    let listener = net.listen(":9000");
    let conn = listener.accept();
    let data = conn.read();
    conn.write(data);
    conn.close();
}

Contents

Functions

Function listen

pub fn listen(addr: string) -> Listener

Create a TCP listener bound to the given address.

The address format is "host:port" or ":port".

Examples

let listener = net.listen(":9000");

Function try_listen

pub fn try_listen(addr: string) -> Result<Listener, fs.IoError>

Create a TCP listener bound to the given address.

Returns Err(fs.IoError) instead of panicking on bind failure.

Examples

import std::fs;

match net.try_listen(":9000") {
    Ok(ln) => { /* accept connections */ },
    Err(IoError::AddressInUse(_)) => println("port already taken"),
    Err(e) => println("bind failed"),
}

Function connect

pub fn connect(addr: string) -> Connection

Connect to a TCP server at the given address.

Blocks until the connection is established.

Examples

let conn = net.connect("localhost:9000");

Function try_connect

pub fn try_connect(addr: string) -> Result<Connection, fs.IoError>

Connect to a TCP server at the given address.

Returns Err(fs.IoError) instead of panicking on failure.

Examples

import std::fs;

match net.try_connect("localhost:9000") {
    Ok(conn) => { /* use conn */ },
    Err(IoError::ConnectionRefused(_)) => println("nothing listening"),
    Err(e) => println("connect failed"),
}

Function connect_timeout

pub fn connect_timeout(addr: string, timeout_sec: i64, timeout_usec: i64) -> Connection

Connect to a TCP server with a timeout.

timeout_sec and timeout_usec specify the deadline.

Function broadcast_except

pub fn broadcast_except(sender: Connection, message: bytes) -> i64

Broadcast a message to all connections except the sender.

Used in chat-server patterns to fan out messages.

Function try_broadcast_except

pub fn try_broadcast_except(sender: Connection, message: bytes) -> Result<i64, fs.IoError>

Broadcast a message to all connections except the sender.

Used in chat-server patterns to fan out messages.

Types

Struct Listener

A TCP listener bound to an address, waiting for connections.

Created by net.listen(addr). Returns a negative value (as i32) on failure when cast; use comparison to check success.

Struct Connection

An established TCP connection for reading and writing.

Obtained from listener.accept() or net.connect(addr).

Struct StreamPair

Opaque paired stream/sink handle returned by hew_tcp_stream_from_conn. Extract the two halves with hew_stream_pair_stream_bytes / hew_stream_pair_sink_bytes, then free with hew_stream_pair_free.

Traits

Trait ListenerMethods

Methods available on a TCP Listener.

Methods

fn accept(self: Self) -> Connection

Block until a client connects and return the new Connection.

fn close(self: Self)

Close the listener and release the listening socket.

Trait ConnectionMethods

Methods available on a TCP Connection.

Methods

fn read(self: Self) -> bytes

Read raw bytes from the connection.

Blocks until data is available. Returns an empty bytes buffer on EOF or disconnect.

fn read_string(self: Self) -> string

Read a UTF-8 string from the connection.

Convenience wrapper that reads bytes and converts to string.

fn write(self: Self, data: bytes)

Write raw bytes to the connection.

fn write_string(self: Self, data: string)

Write a UTF-8 string to the connection.

Convenience wrapper that converts the string to bytes before sending.

fn close(self: Self)

Close the connection and release resources.

fn set_read_timeout(self: Self, ms: i64) -> Result<(), fs.IoError>

Set the read timeout in milliseconds.

Pass a negative value to clear the timeout.

fn set_write_timeout(self: Self, ms: i64) -> Result<(), fs.IoError>

Set the write timeout in milliseconds.

Pass a negative value to clear the timeout.

fn send(self: Self, data: bytes)

Send raw bytes to the connection (active-mode-paired name for write).

Identical to write, named send to match the active-mode actor idiom: an actor that has attached a connection writes outbound data with conn.send(...) while the runtime delivers inbound data to its on_data handler.

fn send_string(self: Self, data: string)

Send a UTF-8 string to the connection (active-mode-paired name for write_string).

fn attach(self: Self, handler: LocalPid<ConnectionHandler>)

Attach this connection to an actor for Erlang-style active mode.

After this call the runtime reads the socket on a background reactor thread and delivers each inbound chunk to the actor as an on_data(bytes) message (on_data_type), and a single on_close() message (on_close_type) when the peer disconnects or the socket errors. The actor must NOT call blocking read/read_string after attach — the reactor owns the read side — but send/write remain valid for outbound data until the connection closes.

handler is the actor implementing [ConnectionHandler]. The compiler synthesises the on_data / on_close msg_ids (SipHash-1-3 over each handler's fully-qualified name) from the concrete actor type behind the LocalPid, so the caller writes only conn.attach(handler).

This is the substrate that lets a networked actor serve many idle connections without stranding a scheduler worker in a blocking read.

On wasm32 targets this method is unavailable; the type checker rejects calls to Connection methods with WasmUnsupportedFeature::TcpNetworking before codegen (WASM-TODO(#1451)).

fn into_stream_sink(self: Self) -> (Stream<bytes>, Sink<bytes>)

Consume the connection and produce a (Stream<bytes>, Sink<bytes>) pair backed by the same TCP socket.

After this call, the original conn binding is statically unusable (move discipline: the Connection is consumed, matching Closable::close). The original handle is released from the TCP connection table as part of the bridge call — the returned stream and sink each own an independent socket clone.

The returned pair composes with stream.chunks(), stream.take(n), and for await loops. Once select{} stream-next arms land, TCP streams compose directly in select{} without a separate poll loop.

Call conn.set_read_timeout(ms) before into_stream_sink if this stream will be used inside select{}: the park thread cannot interrupt a blocked TcpStream::read without a timeout.

If the factory returns a null pair (invalid fd), the extracted stream and sink are also null. Check with stream.is_valid(s) / sink.is_valid(k) before use.

On wasm32 targets this method is unavailable; the type checker rejects calls to Connection methods with WasmUnsupportedFeature::TcpNetworking before any codegen is reached (WASM-TODO(#1451)).

Trait ConnectionHandler

Trait for actors that handle a TCP connection in active mode.

Implement this on an actor (declare matching receive fn on_data(bytes) / receive fn on_close()) and call conn.attach(this) to have the runtime deliver socket data as actor messages. The actor never calls read — the runtime reads in a background reactor thread — but it may call conn.send(...) for outbound data.

Declared pub so the type checker can recognise that a concrete actor's receive fns structurally satisfy this handler trait at the LocalPid<Actor>LocalPid<ConnectionHandler> coercion site (the conn.attach(this) surface).

Example

actor Echo {
    let conn: Connection;
    receive fn on_data(data: bytes) {
        conn.send(data);
    }
    receive fn on_close() {
        println("client disconnected");
    }
}

Methods

fn on_data(data: bytes)

Called when a chunk of bytes arrives from the peer.

fn on_close()

Called once when the connection closes or errors.