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:
Event | Parameters | Description |
---|---|---|
on-open | socket | WebSocket is first opened. |
on-message | socket message | Server receives a message. |
on-pong | socket buffer | Server receives a 'PONG' frame. |
on-error | socket throwable | An error occurs. |
on-close | socket code reason | The WebSocket is closed. |
There is also an optional ring.websocket.protocols/PingListener
protocol that adds the following event:
Event | Parameters | Description |
---|---|---|
on-ping | socket buffer | Server receives a 'PING' frame. |
The parameters have the following types:
Parameter | Type |
---|---|
socket | satisfies ring.websocket.protocols/Socket |
message | java.lang.CharSequence or java.nio.ByteBuffer |
buffer | java.nio.ByteBuffer |
code | int |
reason | String |
Sockets
A socket is passed to each listener function. Sockets allow you to respond to messages, or close the WebSocket.
Function | Description |
---|---|
(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). |