Advanced · 18 min
Open a realtime channel
Connect, consume messages, and disconnect a WebSocket cleanly.
You’ll buildA reconnecting WebSocket with heartbeat and structured message consumption.
1
Step 1
Choose lifecycle policies
Reconnect and heartbeat behavior belongs in explicit configuration.
let configuration = WebSocketConfiguration(
url: URL(string: "wss://ws.postman-echo.com/raw")!,
reconnectPolicy: .init(maxAttempts: 2),
heartbeatPolicy: .init()
)2
Step 2
Connect and send
Connection and outbound work are async and throwable.
let socket = WebSocketClient(configuration: configuration)
try await socket.connect()
try await socket.send(.text("hello from Nova"))3
Step 3
Consume as a stream
Messages arrive through AsyncThrowingStream and follow task cancellation.
let messages = await socket.messages()
for try await message in messages {
print(message)
break
}
await socket.disconnect(reason: "tutorial-complete")Tutorial complete