HSSocket
TypeA 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
localHost
The local address of the connection, or null if the socket isn't connected over TCP.
localPort
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
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.
connectTimeout
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
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.
The callback receives the event name, the socket, and event-specific arguments:
"connected"-connect()/connectUnix()succeeded."listening"-listen()/listenUnix()succeeded, andlocalPortis now set."connection"- a listening socket accepted a connection; the third argument is the newHSSocket, which has the same callback. Queue a read on it to start receiving."data"- a read completed; the third argument is aUint8Arrayand the fourth is the read's tag."error"- something went wrong; the third argument is a description. If it ended the connection, a"disconnected"event follows."disconnected"- the connection closed, or the socket stopped listening, for any reason, including callingdisconnect(). 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. |
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. |
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. |
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. |
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. |
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. |
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. |
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". |
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. |
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. |
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. |
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. |
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. |
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
sock.write("QUIT\r\n").disconnect()
destroy() -> None
Disconnects the socket and releases its callback. Unlike disconnect(), the callback isn't
called.
destroy() -> None
sock.destroy()