Liking cljdoc? Tell your friends :D

Server Sent Events

Introduction

Server Sent Events (SSE) is a part of the HTML5 generation of specifications that describes a capability for delivering events, asynchronously, from a server to a browser or other user-agent, over a long-lived connection.

SSE conceptually similar to web sockets. However, a key difference is that SSE is layered upon HTTP and thus inherits the protocol’s support for proxying, authorization, cookies and is integrated with Cross-Origin Resource Sharing (CORS).

In contrast, web sockets are raw TCP sockets that share nothing with HTTP except for the ability for a user agent to use the HTTP protocol to initiate a web socket connection. After that, everything is up to agreements between the client and server.

Since yada is designed to support HTTP, it does not provide anything extra to support web sockets beyond that which is provided by the web server.

SSE with yada

To create Server Sent Event streams with yada, return a stream of data from a response.

For example, a stream of data could be a core.async channel. It is important that you set the representation to be text/event-stream, so that a client recognises this as a Server Sent Event stream and keeps the connection open.

(require '[clojure.core.async :refer [chan]])

{:methods {:get {:produces "text/event-stream"
                 :response (chan)}}}

It is, however, highly unusual to want to provide a channel of data to a single client. Typically, what is required is that each client gets a copy of every message in the channel. This can be achieved easily by multiplexing the channel with clojure.core.async/mult, which yada will recognise and tap on your behalf.

(require '[clojure.core.async :refer [mult]])

(let [mlt (mult channel)]
  {:methods {:get {:produces "text/event-stream"
                   :response mlt}}})

Of course, you can tap the mult yourself in your own logic and provide the tapping channel directly to yada, which will 'do the right thing' depending on what you provide.

Can you improve this documentation?Edit on GitHub

cljdoc is a website building & hosting documentation for Clojure/Script libraries

× close