std.net
TCP connections: listening, connecting, and reading and writing text.
import std.net
let listener: net.Listener = net.listen("127.0.0.1", 8080)?
let conn: net.Conn = listener.accept()?
let line: string = conn.read_line()?
conn.write("you said: " + line + "\n")?
conn.close()Everything that can fail returns a Result whose error says what went wrong, for example "cannot connect to example.com:81: timed out".
Types
struct Listener
pub struct Listener {
// and private fields
}A socket that waits for connections.
Methods
pub fn accept(self) -> Result[Conn, string]Waits for the next connection.
pub fn next_ready(self, idle_millis: i64) -> Result[Conn, string]The next connection with something to read: a new one, or one given back with keep whose other side sent more. Kept connections that stay quiet for idle_millis, or that the other side closes, are closed. A server can wait this way without one quiet client keeping the others out.
pub fn keep(self, conn: Conn)Gives a connection back, for next_ready to return when the other side sends more. A listener keeps at most 256; more close the oldest.
pub fn port(self) -> i64The port it listens on.
pub fn close(self)Stops listening.
struct Conn
pub struct Conn {
// and private fields
}A connection to another program.
Methods
pub fn read_bytes(self, count: i64) -> Result[List[u8], string]Exactly count bytes, for binary protocols.
pub fn write_bytes(self, data: List[u8]) -> Result[i64, string]Writes bytes; the number written.
pub fn read_until(self, delimiter: string) -> Result[string, string]The text before delimiter, which is read and dropped. Waits until the delimiter arrives.
pub fn read_until_max(self, delimiter: string, max: i64) -> Result[string, string]Like read_until, but fails with "message too large" when more than max bytes come before the delimiter, so a client cannot fill the memory.
pub fn read_line(self) -> Result[string, string]The next line, without its line ending (\n or \r\n).
pub fn read_exact(self, count: i64) -> Result[string, string]Exactly count bytes, as text.
pub fn read_all(self) -> Result[string, string]Everything until the other side closes the connection.
pub fn write(self, text: string) -> Result[i64, string]Sends text; returns the number of bytes sent.
pub fn set_timeout(self, millis: i64) -> Result[i64, string]Gives up reading or writing after this many milliseconds (0: wait forever, the default).
pub fn port(self) -> i64The local port of the connection.
pub fn close(self)Closes the connection.
Functions
fn closed
pub fn closed() -> ConnA connection that is not open: reading from it and writing to it fail.
fn listen
pub fn listen(host: string, port: i64) -> Result[Listener, string]Listens for connections on a host and port. Use "127.0.0.1" for this computer only, or "0.0.0.0" for every network; port 0 picks a free port (see Listener.port).
fn connect
pub fn connect(host: string, port: i64) -> Result[Conn, string]Connects to a host and port.