WebSocket

A handler answers an upgrade request with Ring 1.11's :ring.websocket/listener, and plumeria answers 101 and runs the socket on the connection's fiber. Code written for ring.websocket (ring-core) runs as is, and a plain map listener works without ring-core loaded:

(require '[ring.websocket :as ws])   ; ring-core, for send/close and upgrade-request?

(http/run-server
  (fn [req]
    (if (ws/upgrade-request? req)
      {:ring.websocket/listener
       {:on-open    (fn [socket] (ws/send socket "hello"))
        :on-message (fn [socket message] (ws/send socket message))
        :on-close   (fn [socket code reason] (println "closed" code reason))}}
      {:status 200 :body "not a websocket"}))
  {:port 18090})

The listener's other keys are :on-pong, :on-ping (without one, a ping gets a pong) and :on-error. An implementation of ring.websocket.protocols/Listener works too. Text arrives as a String, binary as a read-only ByteBuffer. :ring.websocket/protocol "chat" in the response answers Sec-WebSocket-Protocol (a token; anything else is left out). Headers on a listener response aren't sent with the 101. A request that isn't a valid handshake gets 400 (426 for a version other than 13), and the listener is never called.

The socket satisfies Ring's Socket and AsyncSocket. A send may come from any fiber or thread: one lock per socket keeps frames whole, async sends go out in the order they were made, and a send after the close throws IOException (or calls the async fail). Listener callbacks run on the connection's fiber one at a time, so a slow on-message holds up pings and closes. Hand long work to a fiber of its own.

Options go under :websocket in run-server's map:

optiondefault
:max-frame1048576a frame declaring more is refused from its header (1009)
:max-message8388608a message over this across fragments is refused (1009)
:ping-ms30000a read that waits this long sends a ping; a second one closes (1001, on-close 1006)
:close-ms2000how long the server waits for the peer's close frame after sending its own

Unmasked client frames, unknown opcodes, reserved bits and bad control frames close with 1002, invalid UTF-8 text with 1007, and a listener callback that throws with 1011 (after :on-error, reported as :websocket-threw). on-close is called exactly once, with 1006 when the peer just vanished. A frame that starts and then stalls for twice :ping-ms closes the socket.

Stopping the server sends 1001 to every open socket and refuses new upgrades with 503. Over HTTPS (wss://) nothing changes, and each TLS connection keeps its records in order when several fibers send at once. Websockets count toward :max-connections and stay under :write-ms. There's no permessage-deflate.

ring/ring-websocket-protocols is plumeria's one runtime dependency: a single file of Ring's protocols, loaded on the first upgrade.