Skip to main content

WebSockets

Experimental support for WebSockets in Ring was added in 1.11.0-alpha1.

Overview

Here's an example of the syntax:

(ns example.websocket
(:require [ring.websocket :as ws]))

(defn echo-handler [request]
(assert (ws/websocket-request? request))
{::ws/listener
{:on-open
(fn [socket]
(ws/send socket "I will echo your messages"))
:on-message
(fn [socket message]
(if (= message "exit")
(ws/close socket)
(ws/send socket message)))}})

The connection is upgraded to a WebSocket when the adapter receives a map with the :ring.websocket/listener key. The associated value of the key must satisfy to the ring.websocket.protocols/Listener protocol. Normal Clojure maps satisfy this protocol, so they are a convenient way of creating a listener.

Listeners

Listeners can handle five events:

EventParametersDescription
on-opensocketWebSocket is first opened.
on-messagesocket messageServer receives a message.
on-pongsocket bufferServer receives a 'PONG' frame.
on-errorsocket throwableAn error occurs.
on-closesocket code reasonThe WebSocket is closed.

There is also an optional ring.websocket.protocols/PingListener protocol that adds the following event:

EventParametersDescription
on-pingsocket bufferServer receives a 'PING' frame.

The parameters have the following types:

ParameterType
socketsatisfies ring.websocket.protocols/Socket
messagejava.lang.CharSequence or java.nio.ByteBuffer
bufferjava.nio.ByteBuffer
codeint
reasonString

Sockets

A socket is passed to each listener function. Sockets allow you to respond to messages, or close the WebSocket.

FunctionDescription
(send socket message)Synchronously send a String, byte array or ByteBuffer to the client.
(send socket message succeed fail)As above, but asynchronously, with callbacks for success or failure.
(ping socket)Ping the client.
(ping socket data)Ping the client with a ByteBuffer of application data.
(pong socket)Send an unrequested pong to the client.
(pong socket data)Send an unrequested pong with a ByteBuffer of application data.
(close socket)Close the WebSocket normally.
(close socket code reason)Close the WebSocket with a custom code (int) and reason (String).