Grav v1.14.0

TCP

import "std/net" (not included in import "std") · namespace std.net

TCP connections, for clients and servers, over IPv4 and IPv6. Sockets are blocking: a read waits until data arrives, which is simple to reason about. Serve several clients by handling each connection on its own Thread.

grav
import "std"
import "std/net"

fn main() {
    let listener = TcpListener.bind("127.0.0.1", 0)     // port 0: any free port
    let server = Thread.spawn(fn() {
        let conn = listener.accept()
        conn.lines(fn(line: string) { conn.writeLine("echo: " + line) })
        conn.close()
    })

    let s = TcpStream.connect("127.0.0.1", listener.port())
    s.writeLine("hello")
    s.writeLine("")
    print(s.readLine())
    print("[" + s.readLine() + "]")
    s.shutdownWrite()                 // the server sees the end of input
    print("[" + s.readLine() + "] eof: ${s.eof()}")
    s.close()
    server.join()
    listener.close()
}
Output
echo: hello
[echo: ]
[] eof: true
  • Connecting: TcpStream.connect(host, port[, timeoutMs]) accepts host names and IPv4/IPv6 addresses. Net.resolve(host) lists a name's addresses.
  • Listening: TcpListener.bind(host, port) (or bind(port) for all interfaces); accept() waits for the next connection. Closing a listener wakes a thread blocked in accept() with a NetError.
  • Reading: readLine() returns "" at the end of input and sets eof(), so an empty line can be told apart from the end. Also read(max), readBytes(max), readExactly(n), readAll() and lines(f); readText(n) reads exactly n bytes straight into a string, and skip(n) drops them (both cheaper than readExactly for framed protocols).
  • Writing: write, writeLine, writeBytes.
  • Options: setTimeoutMs(ms) makes a slow read or write throw TimeoutError; setNoDelay(true) turns off Nagle's algorithm for small, latency-sensitive messages.
  • Errors throw NetError, a subclass of IOError.

Binary data is sent and received as Bytes.

API

class NetError extends IOError

A network failure: refused or reset connections, unknown hosts, and so on.

Constructors

  • new NetError(m: string)

Methods

  • fn kind() -> string — "NetError".

class TcpStream

One TCP connection.

Constructors

  • new TcpStream(fd: int, peer: string)

Static members

  • static fn connect(host: string, port: int) -> TcpStream — Connect to host:port (a name or an IPv4/IPv6 address).
  • static fn connect(host: string, port: int, timeoutMs: int) -> TcpStream — Connect, giving up after timeoutMs milliseconds.

Methods

  • fn write(text: string) — Sends text (NetError when the connection is closed or fails).
  • fn writeLine(text: string) — Sends text followed by "\n".
  • fn writeBytes(data: Bytes) — Sends raw bytes.
  • fn readLine() -> string — The next line (without "\n" or "\r\n"); "" at end of input, with eof() true.
  • fn readLine(maxLen: int) -> string — The next line, at most maxLen bytes long (NetError for a longer one).
  • fn eof() -> bool — True once the peer has closed its side and every buffered byte was read.
  • fn read(max: int) -> string — Up to max bytes as text, waiting for at least one; "" at end of input.
  • fn readBytes(max: int) -> Bytes — Up to max bytes, waiting for at least one; empty at end of input.
  • fn readExactly(n: int) -> Bytes — Exactly n bytes; throws NetError if the stream ends first.
  • fn readText(n: int) -> string — Exactly n bytes as text, copied straight from the read buffer (no Bytes in between); throws NetError if the stream ends first.
  • fn skip(n: int) — Reads and drops exactly n bytes; throws NetError if the stream ends first.
  • fn readAll() -> string — Everything until the peer closes the connection.
  • fn lines(f: fn(string)) — Calls f with each line until end of input.
  • fn setTimeoutMs(ms: int) — Reads and writes that wait longer than ms throw TimeoutError (0 = never).
  • fn setNoDelay(on: bool) — Send small writes immediately (disable Nagle's algorithm).
  • fn peerAddress() -> string — The other side's address ("host:port").
  • fn localPort() -> int — The local port of this connection.
  • fn shutdownWrite() — Stop sending (the peer sees end of input) but keep reading.
  • fn close() — Closes the connection (a second close does nothing).
  • fn handle() -> byte* — The connection's internal state, for lib/net code (TLS).
  • fn fileno() -> int — The socket's file descriptor (for polling it).
  • fn hasBufferedInput() -> bool — Whether input has already arrived that a read would return without waiting (bytes in the buffer, or decrypted TLS data).
  • fn readAvailable(limit: long) -> int — Reads whatever has already arrived, without waiting, into the buffer the read methods take from (until limit bytes are buffered): 1 while the connection is open, 0 once it has ended, -1 after an error. For servers that poll many connections (lib/net/http_server.grav).
  • fn writeNow(data: Bytes, from: int) -> int — Writes as much of data (from byte from on) as the connection takes without waiting, returning how many bytes went (-1 after an error). TLS connections write it all.
  • fn bufferedBytes() -> int — Bytes received and not read yet.
  • fn shedBuffer() — Frees the read buffer (16 KB or more) while nothing unread is in it; the next read makes a new one. A server holding many idle connections calls it as each goes quiet.
  • fn isTls() -> bool — Whether the connection is encrypted with TLS (see lib/net/tls.grav).
  • fn tlsResumed() -> bool — Whether the TLS handshake resumed an earlier session (no full handshake).
  • fn tlsVersion() -> string — The TLS protocol in use ("TLSv1.3"), or "" for a plain connection.
  • fn isClosed() -> bool — Whether close() was called.

class TcpListener

A listening socket that accepts TCP connections.

Constructors

  • new TcpListener(fd: int, host: string)

Static members

  • static fn bind(host: string, port: int) -> TcpListener — Listen on host:port. Port 0 picks a free port (see port()); host "" or "*" listens on every interface. Connections not yet accepted queue up to the system's limit (net.core.somaxconn on Linux), so a burst of thousands at once waits instead of being dropped and retried.
  • static fn bind(port: int) -> TcpListener — Listens on every interface at port (0 picks a free port).

Methods

  • fn fileno() -> int — The listening socket's file descriptor (for polling it).
  • fn port() -> int — The port actually listened on (useful after binding port 0).
  • fn address() -> string — "host:port" this listener is bound to.
  • fn accept() -> TcpStream — Wait for the next connection. Throws NetError once the listener is closed.
  • fn close() — Stop listening; a thread blocked in accept() gets a NetError.
  • fn isClosed() -> bool — Whether the listener was closed.

class Net

Name resolution and other helpers.

Static members

  • static fn hostname() -> string — This machine's host name.
  • static fn reverse(ip: string) -> string — The host name registered for an address (reverse DNS), "" when there is none.
  • static fn isReachable(host: string, port: int, timeoutMs: int) -> bool — Whether a TCP connection to host:port succeeds within timeoutMs.
  • static fn freePort() -> int — A TCP port that is free on this machine right now.
  • static fn resolve(host: string) -> Array<string> — Every address host resolves to (IPv4 and IPv6), as text.

Edit this page on GitHub