Socket
Socket wraps a websocket connection to a relay with status tracking, send and receive queues, and NIP-42 auth state. Sockets are obtained from a Pool rather than constructed directly.
Enums
SocketStatus
Connection status values:
Open- Socket is connected and readyOpening- Socket is connectingClosing- Socket is closingClosed- Socket is closedError- Socket encountered an error
SocketEvent
Event types emitted by the socket:
Error- Socket error occurredStatus- Status changedSend- Message sent to relaySending- Message queued for sendingReceive- Message received from relayReceiving- Message queued for processing
Classes
Socket
Properties:
url- Relay URLstatus- Current socket statusauth- Authentication state
Methods:
open()- Opens the WebSocket connectionattemptToOpen()- Opens connection if not already openclose()- Closes the connectioncleanup()- Closes connection and removes all listenerssend(message)- Queues a message to sendreceive(message)- Queues a message from the relay for processing
Example
typescript
import {Pool, SocketEvent} from "@welshman/net"
const socket = new Pool().get("wss://relay.example.com")
socket.on(SocketEvent.Status, (status, url) => {
console.log(`Socket ${url} status: ${status}`)
})
socket.on(SocketEvent.Receive, (message, url) => {
console.log("Received:", message)
})
socket.open()
socket.send(["REQ", "sub-id", {kinds: [1], limit: 10}])
socket.cleanup()