std::netTCP networking.
Create TCP servers and clients for bidirectional byte-stream
communication. Handle types (Listener, Connection) provide
type-safe wrappers over raw file descriptors.
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"),
}
},
}
}
import std::net;
fn main() {
let listener = net.listen(":9000");
let conn = listener.accept();
let data = conn.read();
conn.write(data);
conn.close();
}
listenCreate a TCP listener bound to the given address.
The address format is "host:port" or ":port".
let listener = net.listen(":9000");
try_listenCreate a TCP listener bound to the given address.
Returns Err(fs.IoError) instead of panicking on bind failure.
import std::fs;
match net.try_listen(":9000") {
Ok(ln) => { /* accept connections */ },
Err(IoError::AddressInUse(_)) => println("port already taken"),
Err(e) => println("bind failed"),
}
connectConnect to a TCP server at the given address.
Blocks until the connection is established.
let conn = net.connect("localhost:9000");
try_connectConnect to a TCP server at the given address.
Returns Err(fs.IoError) instead of panicking on failure.
import std::fs;
match net.try_connect("localhost:9000") {
Ok(conn) => { /* use conn */ },
Err(IoError::ConnectionRefused(_)) => println("nothing listening"),
Err(e) => println("connect failed"),
}
connect_timeoutConnect to a TCP server with a timeout.
timeout_sec and timeout_usec specify the deadline.
broadcast_exceptBroadcast a message to all connections except the sender.
Used in chat-server patterns to fan out messages.
try_broadcast_exceptBroadcast a message to all connections except the sender.
Used in chat-server patterns to fan out messages.
ListenerA 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.
ConnectionAn established TCP connection for reading and writing.
Obtained from listener.accept() or net.connect(addr).
StreamPairOpaque 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.
ListenerMethodsMethods available on a TCP Listener.
Block until a client connects and return the new Connection.
Close the listener and release the listening socket.
ConnectionMethodsMethods available on a TCP Connection.
Read raw bytes from the connection.
Blocks until data is available. Returns an empty bytes buffer on EOF or disconnect.
Read a UTF-8 string from the connection.
Convenience wrapper that reads bytes and converts to string.
Write raw bytes to the connection.
Write a UTF-8 string to the connection.
Convenience wrapper that converts the string to bytes before sending.
Close the connection and release resources.
Set the read timeout in milliseconds.
Pass a negative value to clear the timeout.
Set the write timeout in milliseconds.
Pass a negative value to clear the timeout.
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.
Send a UTF-8 string to the connection (active-mode-paired name for
write_string).
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)).
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)).
ConnectionHandlerTrait 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).
actor Echo {
let conn: Connection;
receive fn on_data(data: bytes) {
conn.send(data);
}
receive fn on_close() {
println("client disconnected");
}
}
Called when a chunk of bytes arrives from the peer.
Called once when the connection closes or errors.