WebSocket Client
PrismNetwork includes a WebSocket client built on Apple’sNetwork.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
ImplementPrismNetworkSocketEndpoint to describe where to connect:
ChatSocketEndpoint.swift
Connecting
PrismNetworkSocketAdapter returns an AsyncStream<Data> of received frames:
Connecting to WebSocket
- Buffering: Incoming data is buffered and split on newline boundaries (
\nor\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 toPrismNetworkSocketCommand:
Chat Commands
Sending Messages
Using Socket Requests
For structured request patterns, usePrismNetworkSocketRequest:
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
Dataframe on the async stream - A trailing newline is automatically appended to outgoing commands if not present
Next Steps
Network Client
HTTP client and type-safe request patterns.
Advanced Features
Request deduplication, offline queues, and GraphQL.