API Docs

A TCP or Unix domain stream socket, created by hs.socket.create().

A socket can either connect to a server (connect()/connectUnix()) or listen for incoming connections (listen()/listenUnix()). Each connection a listening socket accepts is handed to its callback as a new HSSocket, which inherits the listening socket's callback.

Reading is request-driven: queue a read with readUntil(), readBytes() or readAvailable(), and the callback receives a "data" event once that read can be satisfied. Data that arrives before you ask for it is buffered. Reads can be queued before the socket connects, and each one carries an optional numeric tag that is passed back to the callback, so a single callback can tell a protocol's reads apart (e.g. a header and a body).

Received data is delivered as a Uint8Array. Use hs.socket.decodeText() to turn it into a string.

Do not instantiate HSSocket directly - use hs.socket.create().

Properties

identifier

string
A unique identifier for this socket (UUID string).

isConnected

boolean
Whether the socket is currently connected to a peer.

state

string
What the socket is doing.

isListening

boolean
Whether the socket is currently listening for incoming connections.

isSecure

boolean
Whether the socket's connection is encrypted with TLS.

remoteHost

string
The host of the connected peer, or `null` if the socket isn't connected over TCP.

remotePort

number
The port of the connected peer, or 0 if the socket isn't connected over TCP.

localHost

string
The local address of the connection, or `null` if the socket isn't connected over TCP.

localPort

number
The local port of the connection, or the port a listening socket is listening on. 0 if neither applies, including while a listener is still starting up.

unixPath

string
The path of the Unix domain socket this socket is connected to or listening on, or `null` if it isn't using a Unix domain socket.

clients

HSSocket[]
The connections a listening socket has accepted that are still connected.

connectTimeout

number
How long, in seconds, connecting may take, including any TLS handshake. When it expires, the callback receives an `"error"` event and the socket disconnects. 0 (or any negative number) means no timeout. Defaults to `hs.socket.connectTimeout`.

readTimeout

number
How long, in seconds, a queued read may wait with no data arriving. The timer runs only while a read is queued, and restarts whenever data arrives, so a slow but steady transfer doesn't time out, and nor does a connection that's quiet while no read is queued. When it expires, the callback receives an `"error"` event and the socket disconnects. 0 (or any negative number) means no timeout. Defaults to `hs.socket.readTimeout`.

Methods

setCallback(callback) -> HSSocket

Sets the callback that receives this socket's events. `HSSocket`, which has the same callback. Queue a read on it to start receiving. read's tag. connection, a `"disconnected"` event follows. reason, including calling `disconnect()`. Data received that no read had asked for yet is discarded. An `"error"` event on its own never changes the socket's state: errors such as calling `connect()` on a socket that is already connecting, or writing to an idle socket, leave it as it was. Every connection that ends, and every listening socket that stops, gets a `"disconnected"` event, after the `"error"` that caused it, if any. So reconnecting belongs in the `"disconnected"` handler, not the `"error"` one. When the peer closes the connection, data already received for the first queued read is delivered to it in a last `"data"` event, before `"disconnected"`, even though the read isn't satisfied: it may be missing its delimiter, or be shorter than asked for. This is how to receive the end of a stream that the peer ends by closing, such as an HTTP/1.0 response body.
setCallback(callback) -> HSSocket
Name Type Description
callback function | null The event handler, or `null` to remove it.
HSSocket
The socket, for chaining.
sock.setCallback((event, sock, data, tag) => {
    if (event === "data") console.log(hs.socket.decodeText(data))
})

connect(host, port) -> HSSocket

Connects to a TCP server. The callback receives `"connected"` once the connection is ready, or `"error"` if it fails.
connect(host, port) -> HSSocket
Name Type Description
host string The host name or IP address to connect to.
port number The TCP port to connect to.
HSSocket
The socket, for chaining.
A connected socket, and its callback, stay alive until it disconnects, even if you don't keep a reference to it
hs.socket.create().setCallback((event, sock, data) => {
    if (event === "connected") sock.write("GET / HTTP/1.0\r\n\r\n").readUntil("\r\n\r\n")
    if (event === "data") console.log(hs.socket.decodeText(data))
}).connect("example.com", 80)

connectUnix(path) -> HSSocket

Connects to a Unix domain socket. The callback receives `"connected"` once the connection is ready, or `"error"` if it fails.
connectUnix(path) -> HSSocket
Name Type Description
path string The path of the Unix domain socket.
HSSocket
The socket, for chaining.
A connected socket, and its callback, stay alive until it disconnects, even if you don't keep a reference to it
hs.socket.create().setCallback(handler).connectUnix("/var/run/mysql.sock")

listen(port, address) -> HSSocket

Listens for incoming TCP connections. The callback receives `"listening"` once the socket is ready, then `"connection"` for each client that connects. By default the socket listens on all network interfaces. Pass one of this Mac's IP addresses to accept connections only on that address (and so only on the interface that has it), e.g. `"127.0.0.1"` to accept connections only from this Mac. Use `hs.network.addresses()` to find an interface's addresses. If the interface's address can change (e.g. it comes from DHCP), watch `State:/Network/Interface/<name>/IPv4` with `hs.network.configurationWatcher()` and listen again when it does.
listen(port, address) -> HSSocket
Name Type Description
port number The TCP port to listen on, or 0 to let the system choose one (see `localPort`).
address string A local IPv4 or IPv6 address to listen on. Defaults to all addresses.
HSSocket
The socket, for chaining.
A listening socket, and its callback, stay alive until it stops listening, even if you don't keep a reference to it
hs.socket.create().setCallback((event, sock, data) => {
    if (event === "connection") data.write("Hello!\n").readUntil("\n")
    if (event === "data") sock.write(data)
}).listen(9000)

// Only reachable from this Mac
hs.socket.create().setCallback(handler).listen(9001, "127.0.0.1")

listenUnix(path) -> HSSocket

Listens for incoming connections on a Unix domain socket. A stale socket file left at `path` is replaced, and the file is removed when the socket stops listening.
listenUnix(path) -> HSSocket
Name Type Description
path string The path to create the Unix domain socket at.
HSSocket
The socket, for chaining.
A listening socket, and its callback, stay alive until it stops listening, even if you don't keep a reference to it
hs.socket.create().setCallback(handler).listenUnix("/tmp/hammerspoon.sock")

enableTLS(peerName, allowUntrusted) -> HSSocket

Makes the next `connect()` use TLS. The server's certificate is checked against the system's trusted certificates and against `peerName`, or the host passed to `connect()`.
enableTLS(peerName, allowUntrusted) -> HSSocket
Name Type Description
peerName string The name the server's certificate must match, if it differs from the host you connect to.
allowUntrusted boolean `true` to accept any certificate, e.g. a self-signed one. This makes the connection vulnerable to interception, so only use it for testing.
HSSocket
The socket, for chaining.
hs.socket.create().enableTLS().setCallback(handler).connect("example.com", 443)

enableServerTLS(path, passphrase) -> HSSocket

Makes the next `listen()` use TLS, presenting the certificate and private key stored in a PKCS#12 (`.p12`) file. If the file can't be loaded, `listen()` reports an error instead of listening without encryption. A PKCS#12 file can be exported from Keychain Access, or made from a certificate and key with `openssl pkcs12 -export -in cert.pem -inkey key.pem -out server.p12`.
enableServerTLS(path, passphrase) -> HSSocket
Name Type Description
path string The path to the PKCS#12 file.
passphrase string The passphrase protecting the file. Defaults to an empty passphrase.
HSSocket
The socket, for chaining.
TLS isn't supported on Unix domain sockets, so `listenUnix()` reports an error if this has been called
hs.socket.create().setCallback(handler).enableServerTLS("~/.config/server.p12", "secret").listen(8443)

enableServerTLSFromKeychain(name) -> HSSocket

Makes the next `listen()` use TLS, presenting a certificate and private key (an identity) from the keychain. The identity is found by its certificate's name, as Keychain Access shows it (usually the certificate's common name). If no identity has that name, `listen()` reports an error instead of listening without encryption.
enableServerTLSFromKeychain(name) -> HSSocket
Name Type Description
name string The name of the certificate, e.g. `"myhost.local"`.
HSSocket
The socket, for chaining.
macOS may ask for permission to use the private key the first time a client connects
TLS isn't supported on Unix domain sockets, so `listenUnix()` reports an error if this has been called
hs.socket.create().setCallback(handler).enableServerTLSFromKeychain("myhost.local").listen(8443)

readUntil(delimiter, tag) -> HSSocket

Queues a read that completes once `delimiter` arrives. The callback receives the data up to and including the delimiter.
readUntil(delimiter, tag) -> HSSocket
Name Type Description
delimiter string The text that ends the read, e.g. `"\n"`. It is matched as UTF-8 bytes.
tag number A number passed back to the callback with the data. Defaults to 0.
HSSocket
The socket, for chaining.
sock.readUntil("\r\n", 1)

readBytes(length, tag) -> HSSocket

Queues a read that completes once exactly `length` bytes have arrived.
readBytes(length, tag) -> HSSocket
Name Type Description
length number The number of bytes to read.
tag number A number passed back to the callback with the data. Defaults to 0.
HSSocket
The socket, for chaining.
sock.readBytes(4, 2)

readAvailable(tag) -> HSSocket

Queues a read that completes with whatever data is available, as soon as there is any.
readAvailable(tag) -> HSSocket
Name Type Description
tag number A number passed back to the callback with the data. Defaults to 0.
HSSocket
The socket, for chaining.
sock.readAvailable()

write(text) -> HSSocket

Sends text over the connection, encoded as UTF-8. Writes are sent in order, and can be made before the connection is ready.
write(text) -> HSSocket
Name Type Description
text string The text to send.
HSSocket
The socket, for chaining.
sock.write("HELO example.com\r\n")

writeBytes(bytes) -> HSSocket

Sends raw bytes over the connection.
writeBytes(bytes) -> HSSocket
Name Type Description
bytes JSValue The bytes to send. Any typed array is accepted.
HSSocket
The socket, for chaining.
sock.writeBytes(new Uint8Array([0x01, 0x02, 0x03]))

disconnect() -> HSSocket

Closes the connection after sending any data already written, or stops listening. A listening socket also disconnects every client it accepted. Queued reads, and data received that no read has asked for yet, are discarded. The socket can be connected or listen again afterwards.
disconnect() -> HSSocket
HSSocket
The socket, for chaining.
The callback receives `"disconnected"` (for this socket, and for each client of a listening socket) before `disconnect()` returns, so update any state the handler relies on before calling it
sock.write("QUIT\r\n").disconnect()

destroy() -> None

Disconnects the socket and releases its callback. Unlike `disconnect()`, the callback isn't called.
destroy() -> None
None
sock.destroy()