hammerspoon2-docs
    Preparing search index...

    Class HSSocket

    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().

    Index
    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.

    identifier: string

    A unique identifier for this socket (UUID string).

    isConnected: boolean

    Whether the socket is currently connected to a peer.

    isListening: boolean

    Whether the socket is currently listening for incoming connections.

    isSecure: boolean

    Whether the socket's connection is encrypted with TLS.

    localHost: string | null

    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.

    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.

    Protocols where the peer can stay quiet for a long time while a read is queued (e.g. waiting for the next line of a notification stream) usually want no read timeout

    remoteHost: string | null

    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.

    state: "connected" | "listening" | "idle" | "connecting"

    What the socket is doing.

    unixPath: string | null

    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.

    • Connects to a TCP server. The callback receives "connected" once the connection is ready, or "error" if it fails.

      Parameters

      • host: string

        The host name or IP address to connect to.

      • port: number

        The TCP port to connect to.

      Returns 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

    • Connects to a Unix domain socket. The callback receives "connected" once the connection is ready, or "error" if it fails.

      Parameters

      • path: string

        The path of the Unix domain socket.

      Returns 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

    • Disconnects the socket and releases its callback. Unlike disconnect(), the callback isn't called.

      Returns void

    • 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.

      Returns 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

    • 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.

      Parameters

      • path: string

        The path to the PKCS#12 file.

      • Optionalpassphrase: string | null

        The passphrase protecting the file. Defaults to an empty passphrase.

      Returns HSSocket

      The socket, for chaining.

      TLS isn't supported on Unix domain sockets, so listenUnix() reports an error if this has been called

    • 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.

      Parameters

      • name: string

        The name of the certificate, e.g. "myhost.local".

      Returns 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

    • 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().

      Parameters

      • OptionalpeerName: string | null

        The name the server's certificate must match, if it differs from the host you connect to.

      • OptionalallowUntrusted: 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.

      Returns HSSocket

      The socket, for chaining.

    • 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.

      Parameters

      • port: number

        The TCP port to listen on, or 0 to let the system choose one (see localPort).

      • Optionaladdress: string | null

        A local IPv4 or IPv6 address to listen on. Defaults to all addresses.

      Returns 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

    • 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.

      Parameters

      • path: string

        The path to create the Unix domain socket at.

      Returns 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

    • Queues a read that completes with whatever data is available, as soon as there is any.

      Parameters

      • Optionaltag: number

        A number passed back to the callback with the data. Defaults to 0.

      Returns HSSocket

      The socket, for chaining.

    • Queues a read that completes once exactly length bytes have arrived.

      Parameters

      • length: number

        The number of bytes to read.

      • Optionaltag: number

        A number passed back to the callback with the data. Defaults to 0.

      Returns HSSocket

      The socket, for chaining.

    • Queues a read that completes once delimiter arrives. The callback receives the data up to and including the delimiter.

      Parameters

      • delimiter: string

        The text that ends the read, e.g. "\n". It is matched as UTF-8 bytes.

      • Optionaltag: number

        A number passed back to the callback with the data. Defaults to 0.

      Returns HSSocket

      The socket, for chaining.

    • 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, and localPort is now set.
      • "connection" - a listening socket accepted a connection; the third argument is the new HSSocket, which has the same callback. Queue a read on it to start receiving.
      • "data" - a read completed; the third argument is a Uint8Array and 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 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.

      Parameters

      • callback:
            | (
                (
                    event:
                        | "error"
                        | "connected"
                        | "disconnected"
                        | "listening"
                        | "connection"
                        | "data",
                    socket: HSSocket,
                    data?: string | Uint8Array<ArrayBufferLike> | HSSocket,
                    tag?: number,
                ) => void
            )
            | null

        The event handler, or null to remove it.

      Returns HSSocket

      The socket, for chaining.

    • Sends text over the connection, encoded as UTF-8. Writes are sent in order, and can be made before the connection is ready.

      Parameters

      • text: string

        The text to send.

      Returns HSSocket

      The socket, for chaining.

    • Sends raw bytes over the connection.

      Parameters

      • bytes: ArrayBuffer | Uint8Array<ArrayBufferLike>

        The bytes to send. Any typed array is accepted.

      Returns HSSocket

      The socket, for chaining.