WebSockets

On this page

The WebSockets target serves RFC 6455 WebSockets inside your own Swift server: one WebSocketUpgrade component answers the opening handshake over HTTP/1.1 (Upgrade), HTTP/2 (RFC 8441 extended CONNECT) and HTTP/3 (RFC 9220 extended CONNECT), then runs a WebSocket session that your handler reads and writes with async/await. It validates frames, masking and UTF-8, reassembles fragmented messages, answers pings, runs the close handshake, applies backpressure in both directions and optionally compresses messages (permessage-deflate, RFC 7692).

The short version is in Dynamic websites; this guide is the in-depth one.

You wantUse
A WebSocket endpoint whose logic is Swift running in the serverWebSocketUpgrade in a custom server package (this guide)
To put an existing WebSocket app (Node, Go, Python, another server) behind PhotonHTTPThe shipped executable's reverse proxy with "websocket": true on a mount (below)

In-process endpoints need Swift code. http-config.json has no key that defines a WebSocket endpoint, and the shipped photon executable does not link the WebSockets target; the config file can only proxy WebSockets to a backend. There is also no WebSockets package trait: it was removed because there was nothing for it to switch (issue #0130, Choosing components).

Depend on the target

// Package.swift of your server
dependencies: [
    .package(url: "https://github.com/brennanMKE/PhotonHTTP.git", branch: "main"),
],
targets: [
    .executableTarget(name: "MySite", dependencies: [
        .product(name: "HTTPCore", package: "PhotonHTTP"),
        .product(name: "HTTP1", package: "PhotonHTTP"),
        .product(name: "HTTPServer", package: "PhotonHTTP"),
        .product(name: "NetworkTransport", package: "PhotonHTTP"),
        .product(name: "WebSockets", package: "PhotonHTTP"),
        // .product(name: "HTTP2", …), .product(name: "HTTP3", …) for h2 and h3 WebSockets
    ]),
]

WebSockets depends only on HTTPCore and Compression (zlib, for permessage-deflate). It does not depend on any protocol target: the session runs over whatever byte stream the protocol hands it. Examples/custom-server is a complete package with a /ws echo next to a router and static files.

A first endpoint: echo

import HTTP1
import HTTPCore
import HTTPServer
import NetworkTransport
import WebSockets

@main
struct EchoServer {
    static func main() async throws {
        let echo = WebSocketUpgrade(path: "/ws") { socket, request in
            for await message in socket.messages {
                try await socket.send(message)        // .text or .binary, as received
            }
            // messages ended: the peer closed, the connection dropped, or the server is shutting down
        }
        let listener = try BSDSocketListener(configuration: .init(host: "127.0.0.1", port: 8080))
        let server = Server(listeners: [listener], protocols: [HTTP1()]) {
            echo
            NotFoundHandler()       // everything that is not /ws
        }
        try await server.run()
    }
}
websocat ws://127.0.0.1:8080/ws     # type a line, get it back

Put WebSocketUpgrade before the components that would otherwise answer its path (a Router, StaticFiles). Requests on other paths pass through it untouched. Middleware such as Compression leaves the handshake response (a .tunnel body) alone, so the order relative to it does not matter.

The session API

The handler gets a WebSocket and a WebSocketRequest, and runs for the life of the connection.

MemberWhat it does
messagesAsyncSequence of WebSocketMessage: .text(String) (already validated UTF-8) or .binary(ByteBuffer), in order, each a complete (reassembled, inflated) message. Ends when the connection closes. Iterate it from one task at a time
send(_ message:), send(text:), send(binary:)Sends one message as one frame. Suspends while the outbound queue is full. Throws WebSocketError.closed once the connection is closing or closed
ping(_ payload: ByteBuffer = ByteBuffer(), timeout: Duration = .seconds(10))Sends a ping and waits up to timeout for the pong with the same payload. Payload at most 125 bytes (WebSocketError.pingPayloadTooLong). Throws .pingTimedOut when no pong arrives in time (the connection stays open), .closed if the connection closes first
close(code: = .normalClosure, reason: = "")Starts the close handshake and returns once the Close frame is queued. The reason is at most 123 UTF-8 bytes (.closeReasonTooLong); the code must be sendable (.invalidCloseCode, see close codes). Closing a connection that is already closing does nothing
state.open, .closing (we sent Close, waiting for the peer's) or .closed
closeCode, closeReasonWhat the peer closed with: its code, 1005 for a Close with no code, 1006 if the stream ended without a Close; nil while no Close was received
failureCodeSet when the peer violated the protocol and the server failed the connection
subprotocol, compression, connectionInfo, configurationWhat the handshake agreed, the connection's addresses, the limits in force

The WebSocketRequest owns copies of what the handshake carried, so it stays valid for the whole session: path (still percent-encoded), query (without ?), origin, offeredSubprotocols, headers (every request field) and connection (addresses).

Lifecycle

The handler…The session…
returns while the connection is opencloses it with 1000 (normal closure)
throwscloses it with 1011 (internal error)
is still running when the server shuts downstarts the close handshake with 1001 (going away); messages ends once the peer answers or closeTimeout passes
stops iterating messages but keeps runningdrops buffered and later messages, so reading the socket never stalls on it

Messages still buffered when the handler returns are dropped. The session reads, writes and times the close handshake in child tasks of one task group; nothing outlives the handler and the connection.

send and ping can be called from any task (the outbound side is a queue); only the iteration of messages must stay in one task at a time.

Sending

try await socket.send(text: "hello")
try await socket.send(binary: ByteBuffer(bytes: [0x01, 0x02, 0x03]))
try await socket.send(.text(#"{"type":"ready"}"#))

Each message goes out as a single frame; the server never fragments what it sends, and there is no size limit on outgoing messages (the client may have one). Text is sent as its UTF-8 bytes.

Ping and pong

Pings from the client are answered automatically with a pong carrying the same payload; your handler never sees them. The session also keeps the connection alive by itself (see keepalive below), so most handlers never ping.

ping() is for the server's own checks, such as measuring round-trip time. It waits up to timeout (10 s by default) for the matching pong and throws WebSocketError.pingTimedOut when none arrives; the connection stays open and what to do next is your call:

do {
    try await socket.ping(timeout: .seconds(5))
} catch WebSocketError.pingTimedOut {
    try await socket.close(code: .policyViolation, reason: "no pong")
}

ping() is cancellable, and a pong answers every waiting ping with the same payload. Control frames do not wait for your handler to read messages: the session answers pings and sees pongs and Close frames while messages wait unread, up to the next data frame (see backpressure).

Keepalive

WebSocketConfiguration.keepalive (on by default) pings a quiet peer and drops one that has gone away:

So a vanished peer (a laptop lid closed, a phone that lost coverage, a NAT that forgot the mapping) holds its session for at most 30 s, over any protocol. The 20 s interval also keeps an HTTP/3 WebSocket below QUIC's 30 s idle timeout, and clients' pongs keep NATs and proxies with 60 s idle timeouts from dropping the connection. Browsers and URLSessionWebSocketTask answer pings without any code on the client side.

var configuration = WebSocketConfiguration()
configuration.keepalive = .init(interval: .seconds(10), timeout: .seconds(5))   // mobile clients
// configuration.keepalive = nil                                                // off
WebSocketUpgrade(path: "/live", configuration: configuration) { socket, _ in /* … */ }

Keep interval below the shortest idle timeout on the path: QUIC's (QUICConfiguration.idleTimeoutMilliseconds, 30 s by default) for HTTP/3, and any load balancer's in front of the server. Turn it off only when the application pings on its own schedule.

Closing

try await socket.close()                                         // 1000, no reason
try await socket.close(code: .goingAway, reason: "deploying")
try await socket.close(code: WebSocketCloseCode(rawValue: 4001), reason: "token expired")   // private use

After close, state is .closing, send throws .closed, data frames from the peer are discarded, and messages ends when the peer's Close arrives or closeTimeout (5 s) passes, after which the transport is closed anyway. When the peer closes first, the server echoes its code (without a reason, as RFC 6455 §5.5.1 allows) and closes the connection; read socket.closeCode and socket.closeReason after the loop to see why.

Backpressure

Both directions are bounded, so a slow side slows the other instead of growing memory:

Example: a JSON chat room

A broadcast endpoint needs the set of open sockets shared between sessions. WebSocket is a Sendable class, so a Mutex-protected dictionary works:

import Foundation          // JSONEncoder/Decoder in your handler code
import Synchronization
import WebSockets

final class ChatRoom: Sendable {
    private let members = Mutex<[ObjectIdentifier: WebSocket]>([:])

    func join(_ socket: WebSocket) { members.withLock { $0[ObjectIdentifier(socket)] = socket } }
    func leave(_ socket: WebSocket) { _ = members.withLock { $0.removeValue(forKey: ObjectIdentifier(socket)) } }

    /// Sends to every member concurrently; one slow member delays this call, not the others.
    func broadcast(_ text: String) async {
        let sockets = members.withLock { Array($0.values) }
        await withDiscardingTaskGroup { group in
            for socket in sockets {
                group.addTask { try? await socket.send(text: text) }   // .closed for members on their way out
            }
        }
    }
}

struct Incoming: Decodable { var name: String; var text: String }
struct Outgoing: Encodable { var name: String; var text: String; var at: Date }

let room = ChatRoom()
let chat = WebSocketUpgrade(
    path: "/chat",
    configuration: WebSocketConfiguration(maxMessageSize: 64 * 1024),     // chat lines, not files
    origin: { $0.origin == "https://chat.example.com" }
) { socket, _ in
    room.join(socket)
    defer { room.leave(socket) }
    let decoder = JSONDecoder(), encoder = JSONEncoder()
    for await message in socket.messages {
        guard case .text(let text) = message,
              let incoming = try? decoder.decode(Incoming.self, from: Data(text.utf8)) else {
            try await socket.close(code: .unsupportedData, reason: "expected JSON text")
            continue                                      // messages ends once the client answers
        }
        let out = Outgoing(name: incoming.name, text: incoming.text, at: Date())
        await room.broadcast(String(decoding: try encoder.encode(out), as: UTF8.self))
    }
}

broadcast waits for the slowest member's outbound queue. For rooms with clients you do not control, bound it (race each send against a timer in a task group) and close members that fall behind with .policyViolation or .tryAgainLater.

The opening handshake

Path matching

WebSocketUpgrade(path:) compares the request path byte for byte, still percent-encoded and without the query (/ws?room=1 matches path: "/ws"; read the query from request.query). There are no patterns or prefixes; use one component per endpoint, or path: nil and branch on request.path in the handler.

Requestpath: "/ws"path: nil
Another pathNext handlerNext handler if it has no Upgrade: websocket, otherwise handled here
The path, valid handshake101 (HTTP/1.1) or 200 (extended CONNECT), session startssame
The path, GET without Upgrade: websocket426 Upgrade Required with Upgrade: websocketNext handler
The path, Sec-WebSocket-Version missing, repeated or not 13426 with Sec-WebSocket-Version: 13 (400 with that field over extended CONNECT)same
Not GET, no upgrade token in Connection, bad Sec-WebSocket-Key (missing, repeated, not base64 of 16 bytes), HTTP/1.0400same
Rejected by origin403same

HTTP/1.0 requests are never upgraded (RFC 9110 ignores Upgrade there). Frames a client sends right behind its handshake request, before seeing 101, are kept and replayed into the session.

Origin checks

Browsers send Origin with every WebSocket handshake, and a WebSocket is not subject to CORS: any page can open one to your server, with the user's cookies. If the endpoint relies on cookies or other ambient credentials, check the origin:

let allowed: Set<String> = ["https://example.com", "https://www.example.com"]
WebSocketUpgrade(path: "/ws", origin: { request in
    guard let origin = request.origin else { return false }   // false also rejects non-browser clients
    return allowed.contains(origin)
}) { socket, request in … }

origin returns false → 403, and the handler never runs. It sees the whole WebSocketRequest, so it is also the place for other accept/reject decisions made from the request alone (a token in the query or a header). Authentication middleware (Auth) placed before the component applies too.

Subprotocols

The client lists subprotocols in Sec-WebSocket-Protocol, in its order of preference; they arrive as request.offeredSubprotocols. subprotocol picks one:

WebSocketUpgrade(path: "/rpc", subprotocol: { request in
    ["v2.rpc.example", "v1.rpc.example"].first { request.offeredSubprotocols.contains($0) }
}) { socket, _ in
    switch socket.subprotocol {
    case "v2.rpc.example": …
    default: …
    }
}

The choice is returned in the response's Sec-WebSocket-Protocol. A choice the client did not offer is ignored (no field is sent), as is nil. Without a subprotocol closure no subprotocol is ever agreed.

Extensions

The only extension is permessage-deflate, accepted when WebSocketConfiguration.compression is set (below). Other extensions in Sec-WebSocket-Extensions are ignored, and frames with RSV bits that no negotiated extension allows fail the connection with 1002.

HTTP/1.1, HTTP/2 and HTTP/3

The same component and handler serve all three; the handshake differs, the session does not.

HTTP/1.1HTTP/2HTTP/3
StandardRFC 6455 §4RFC 8441RFC 9220
Client sendsGET + Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key, Sec-WebSocket-Version: 13CONNECT with :protocol websocket, Sec-WebSocket-Version: 13 (no key)same as HTTP/2
Server answers101 Switching Protocols with Sec-WebSocket-Accept200200
Session runs overthe TCP (or TLS) connection, which is then used for nothing elseone stream; other requests share the connectionone QUIC request stream
Advertised by–SETTINGS_ENABLE_CONNECT_PROTOCOL = 1SETTINGS_ENABLE_CONNECT_PROTOCOL = 1
RegisterHTTP1()HTTP2() (usually TLSNegotiated(HTTP2(), fallback: HTTP1()))HTTP3() on a QUIC listener

HTTP2 and HTTP3 turn SETTINGS_ENABLE_CONNECT_PROTOCOL on by themselves when an ExtendedConnectProvider is anywhere in the handler chain (including inside VirtualHosts); WebSocketUpgrade is one, and so is ReverseProxy when a mount has websocket on. You can also force it with enableConnectProtocol in HTTP2Configuration / H3Configuration. Without the setting, an HTTP/2 request carrying :protocol is reset with PROTOCOL_ERROR and an HTTP/3 one is malformed.

An extended CONNECT's DATA is the tunnel's byte stream, not a request body, so maxRequestBodySize does not apply to it. On HTTP/2, a reset stream ends the session as an abnormal closure (1006); the tunnel's data goes through the stream's flow control like a response body. Listener and TLS setup for h2 and h3 are in Choosing components; the same WebSocket component needs nothing extra.

permessage-deflate

let ws = WebSocketUpgrade(
    path: "/feed",
    configuration: WebSocketConfiguration(compression: PerMessageDeflate.Configuration())
) { socket, _ in
    // socket.compression is nil when the client did not offer the extension
    …
}

With compression set, a client's permessage-deflate offer is accepted and answered in Sec-WebSocket-Extensions; with it nil (the default) the extension is declined and every message travels uncompressed. Compression is per message: each data message the server sends is deflated into one frame with RSV1 set, and RSV1 messages from the client are inflated as their frames arrive. Messages below minimumMessageSize go out uncompressed, as do (without context takeover) messages that do not get smaller.

Negotiation

The client may offer the extension several times with different parameters; the first offer the server can honour is accepted. An offer with an unknown or repeated parameter or an invalid value is declined.

ParameterWhen the client offers itIn the response
server_no_context_takeoverThe server resets its compressor after each messageSent when offered or when serverNoContextTakeover is set
client_no_context_takeoverThe client resets its compressorSent when offered or when clientNoContextTakeover is set
server_max_window_bits=NThe server's window may be at most 2^Nmin(N, serverMaxWindowBits); also sent unasked when serverMaxWindowBits is below 15. An agreed window of 2^8 declines the offer (zlib's raw deflate needs at least 2^9)
client_max_window_bits[=N]The client can limit its windowclientMaxWindowBits when that is below 15 (only if the client offered the parameter)

The server always inflates with a 2^15 window, which decodes whatever window the client uses. URLSessionWebSocketTask on macOS offers a bare permessage-deflate and compresses every message it sends (covered by URLSessionDeflateTests).

PerMessageDeflate.Configuration

FieldDefaultRangeMeaning
serverNoContextTakeoverfalseReset the compressor after every message (always on when the client asks)
clientNoContextTakeoverfalseAsk the client to reset its compressor after every message
serverMaxWindowBits159…15The server's LZ77 window
clientMaxWindowBits158…15The window the client may use
compressionLevel61…9zlib level
memoryLevel81…9zlib memory level (state size and speed)
minimumMessageSize32≥ 0Smaller messages are sent uncompressed

Values out of range trap at initialization.

Cost and when to enable it

From M15-websockets (1,000 typical JSON messages, 124 bytes on average):

SettingStream sizeCompress, per messageInflate, per message
Default (level 6, context takeover)19% of original2.5 µs0.2 µs
Level 126%1.7 µs
Level 918%5.9 µs
Window 2^1029%3.7 µs
server_no_context_takeover86%5.0 µs
client_no_context_takeover0.7 µs

Limits and timeouts

WebSocketConfiguration, passed to WebSocketUpgrade(configuration:):

FieldDefaultWhat happens at the limit
maxFrameSize16 MiBA received frame with a longer payload fails the connection with 1009, decided from the frame header before the payload is buffered. Must be ≥ 125
maxMessageSize16 MiBA received message longer than this after reassembly (and after inflating, with compression) fails the connection with 1009, also detected from frame headers for uncompressed messages
closeTimeout5 sHow long to wait for the peer's Close after ours (or for its end of stream after it closed), then the transport is closed anyway
inboundMessageCapacity1Complete messages buffered for the handler before the session stops reading
outboundFrameCapacity8Frames queued for sending before send suspends
receiveSize64 KiBLargest single read from the transport
compressionnilpermessage-deflate settings; nil declines the extension
keepalive20 s interval, 10 s timeoutA ping after interval without anything from the peer; nothing within timeout after it closes the connection as 1006. nil turns it off. See keepalive

Fragmentation is accepted inbound with any number of fragments, limited only by maxMessageSize; control frames may arrive between fragments. Outbound messages are never fragmented.

Memory per connection is bounded by these numbers: roughly one message being assembled (up to maxMessageSize), inboundMessageCapacity complete messages, outboundFrameCapacity queued frames, the receive buffer, and the zlib state when compression is on. The 16 MiB defaults suit trusted clients; for a public endpoint set maxMessageSize and maxFrameSize to the largest message your protocol needs.

Timeouts, and what ends a quiet connection

The WebSockets component's keepalive (on by default) pings a peer that has been quiet for 20 s and closes the connection when nothing answers within 10 s, over every protocol. A quiet but healthy peer stays connected indefinitely: there is no idle timeout and no handshake-to-first-message timeout. What else applies depends on the protocol under it:

OverWhat applies after the handshake
HTTP/1.1None of HTTP/1.1's timeouts: they stop at 101. A peer that vanishes without a FIN or reset is found by keepalive. With keepalive off it keeps the session until a send fails, unless TCP keep-alive is on for the listener (TCPConfiguration(keepAlive: .init()), off by default; 60 s idle, 10 s interval, 6 probes)
HTTP/2The stream is running, so the connection's idleTimeout does not fire. Each WebSocket counts against maxConcurrentStreams (default 100 per connection). A client that stops reading while the server sends trips windowStallTimeout (30 s by default)
HTTP/3QUIC's idle timeout (QUICConfiguration.idleTimeoutMilliseconds, 30 s by default) closes the connection when no packets flow. Keepalive's 20 s pings keep a quiet WebSocket under it; with keepalive off, or an interval at or above the idle timeout, quiet WebSockets are dropped
Server shutdown1001 to every in-process session, then closeTimeout for the peer's answer, within the server's drainTimeout (10 s by default)

Protocol violations and close codes

A violation by the client fails the connection (RFC 6455 §7.1.7): the server sends a Close with the code below (if it has not sent one yet), closes the transport, and messages ends. socket.failureCode holds the code.

ViolationClose code
Unmasked frame from the client1002
Reserved opcode (3–7, 11–15)1002
RSV bit set without a negotiated extension; RSV1 on a continuation or control frame1002
Control frame fragmented or longer than 125 bytes1002
64-bit length with the most significant bit set1002
Continuation without a message in progress; new text/binary frame inside a fragmented message1002
Close frame with a 1-byte payload, or a code no endpoint may send1002
Text that is not UTF-8 (checked as it arrives, across fragments; the first bad byte fails it), or a message ending inside a code point1007
Close reason that is not UTF-81007
Compressed data that does not inflate1007
Frame over maxFrameSize, message over maxMessageSize (inflated size with compression)1009

Binary messages are not inspected. Overlong (non-minimal) length encodings are accepted, as RFC 6455 leaves them to the sender. A violation while the server is already closing just closes the transport.

Close codes

WebSocketCloseCode has constants for the registered codes:

CodeConstantSent by this server when
1000.normalClosureThe handler returned; your default for close()
1001.goingAwayServer shutdown
1002.protocolErrorProtocol violation (table above)
1003.unsupportedData– (for you: wrong message type)
1005.noStatusReceivedNever sent; reported in closeCode for a Close without a code
1006.abnormalClosureNever sent; reported when the stream ended without a Close, or keepalive found the peer gone
1007.invalidFramePayloadDataInvalid UTF-8 or deflate data
1008.policyViolation– (for you: a generic policy refusal)
1009.messageTooBigFrame or message over the limits
1010.mandatoryExtension– (sent by clients)
1011.internalServerErrorThe handler threw; zlib could not allocate
1012–1014.serviceRestart, .tryAgainLater, .badGateway–
1015.tlsHandshakeNever sent

close(code:) accepts 1000–1003, 1007–1014 and 3000–4999 (3000–3999 are registered with IANA, 4000–4999 are for private use between your server and your clients); anything else throws WebSocketError.invalidCloseCode. The same rule applies to codes received: a Close from the client with 1004–1006, 1015, 1016–2999 or a value outside 1000–4999 is a 1002.

Proxying WebSockets to a backend

The shipped executable forwards WebSockets to an app on localhost when the proxy mount has "websocket": true:

{
  "root": "Public",
  "proxy": [
    { "path": "/socket", "upstream": "http://127.0.0.1:9000", "websocket": true,
      "timeouts": { "connect": 2, "idle": 600 } }
  ]
}
SettingValueMeaning
websocketfalseTunnel WebSocket upgrades on this mount
timeouts.idleabsent: 300 s for tunnelsThe tunnel closes when no byte moves in either direction for this long. Setting it explicitly also sets the tunnel's limit; 0 or null turns it off
Handshake timeout30 s (not configurable in the file)Connecting upstream and reading its answer; 504 on timeout, 502 on a failure
Half-close timeout30 s (not configurable in the file)After one direction ends, how long the other may continue

Long-lived quiet sockets (notifications, dashboards) need "idle": 0 or a value above the interval at which the app or client pings. Since idle also bounds ordinary proxied requests between body reads, consider a separate mount for the WebSocket path. On server shutdown a spliced tunnel is closed at the transport level; the proxy sends no Close frame of its own, so clients see the connection drop (1006) unless the backend closes first. The rest of the proxy (upstreams, stripPrefix, hosts, health checks) is in Dynamic websites; in a custom server the same component is ReverseProxy with a ProxyMount whose websocket is true, and its ProxyTunnelConfiguration exposes the handshake, idle and half-close timeouts and allowedUpgradeProtocols for non-WebSocket upgrades.

Testing

Follow AGENTS.md on the owner's Mac: bind tests to 127.0.0.1 port 0 and run servers through scripts/guarded.sh.

Autobahn

No Autobahn|Testsuite results are recorded in benchmarks/; the protocol rules are covered by the unit tests in Tests/WebSocketsTests (frame parser at every split offset, UTF-8 at every code point boundary, every close code, fragmentation, compression, decompression bombs). To run it yourself you need Docker or wstest, a server with an echo WebSocketUpgrade, and scripts/fuzzingclient.json pointed at it (scripts/run-autobahn-client.sh runs wstest -m fuzzingclient with that file; the URL in it is ws://127.0.0.1:8080 with no path, so give your echo component path: nil or edit the URL). Do not start Docker unattended (see AGENTS.md).

Standards

RFCCoversHere
RFC 6455The WebSocket Protocol: handshake, framing, masking, close codesWebSocketHandshake, WSFrameParser, WSConnection, WebSocket
RFC 7692Compression Extensions for WebSocket (permessage-deflate)PerMessageDeflate
RFC 8441Bootstrapping WebSockets with HTTP/2 (extended CONNECT)HTTP2 + WebSocketUpgrade
RFC 9220Bootstrapping WebSockets with HTTP/3HTTP3 + WebSocketUpgrade
IANA WebSocket Close Code registry1012–1014 and 3000–4999WebSocketCloseCode