Skip to main content

WebSocket Client

PrismNetwork includes a WebSocket client built on Apple’s Network.framework (NWConnection). Define type-safe socket endpoints, connect with an async stream, and send structured commands.

Architecture

PrismNetworkSocketEndpoint

Protocol defining host, port, and NWParameters for a WebSocket connection.

PrismNetworkSocketClient

Protocol with connect(to:) and send(command:) methods.

PrismNetworkSocketAdapter

Actor-based implementation wrapping NWConnection with frame-level buffering.

Defining a WebSocket Endpoint

Implement PrismNetworkSocketEndpoint to describe where to connect:
ChatSocketEndpoint.swift
Use NWParameters to configure TLS, WebSocket protocol options, and connection timeouts. For unencrypted connections, use NWParameters.tcp with WebSocket options.

Connecting

PrismNetworkSocketAdapter returns an AsyncStream<Data> of received frames:
Connecting to WebSocket
The stream automatically handles:
  • Buffering: Incoming data is buffered and split on newline boundaries (\n or \r\n)
  • Clean termination: The stream finishes when the connection closes or fails
  • Cleanup: Disconnecting cancels the underlying NWConnection

Sending Commands

Define typed commands by conforming to PrismNetworkSocketCommand:
Chat Commands
Send commands over the connection:
Sending Messages
send(command:) throws PrismNetworkError.noConnectivity if no active connection exists. Always connect before sending commands.

Using Socket Requests

For structured request patterns, use PrismNetworkSocketRequest:
Socket Request Pattern

Complete Chat Client Example

ChatClient.swift

Using the Chat Client

Using ChatClient

Frame Protocol

PrismNetworkSocketAdapter uses newline-delimited framing:
  • Incoming data is buffered until a \n (or \r\n) delimiter is found
  • Each complete line is emitted as a Data frame on the async stream
  • A trailing newline is automatically appended to outgoing commands if not present
This makes it compatible with JSON-per-line protocols common in real-time applications.

Next Steps

Network Client

HTTP client and type-safe request patterns.

Advanced Features

Request deduplication, offline queues, and GraphQL.