Grav v1.14.0

Unix sockets

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

A Unix domain socket connects programs on the same machine through a file path. It is faster than TCP over localhost, and file permissions decide who may connect. The streams and listeners are the TCP classes, so readLine, write and the rest work the same.

grav
import "std"
import "std/net"

fn main() {
    let path = "/tmp/grav-doc-${Process.pid()}.sock"
    let listener = UnixSocket.listen(path)
    let server = Thread.spawn(fn() {
        let c = listener.accept()
        c.lines(fn(line: string) { c.writeLine(Str.upper(line)) })
        c.close()
    })
    let c = UnixSocket.connect(path)
    c.writeLine("local only")
    print(c.readLine())
    c.shutdownWrite()
    server.join()
    c.close()
    UnixSocket.remove(listener, path)
    print(new File(path).exists())
}
Output
LOCAL ONLY
false
  • UnixSocket.listen(path) creates the socket file, replacing a socket left by an earlier run (but never another kind of file); UnixSocket.remove(listener, path) closes the listener and deletes the file.
  • UnixSocket.connect(path) throws NetError when nothing listens there.
  • Paths are limited to about 100 bytes by the system.

API

class UnixSocket

Unix domain sockets.

Static members

  • static fn connect(path: string) -> TcpStream — Connects to the socket at path (NetError when nothing listens there).
  • static fn listen(path: string) -> TcpListener — Listens at path, replacing a socket file left by an earlier run (but never another kind of file). Delete the file with remove(path) when done.
  • static fn remove(listener: TcpListener, path: string) — Closes listener and deletes its socket file.

Edit this page on GitHub