[[server-sent-events]]
== Server Sent Events

[[sse-introduction]]
=== 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]#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]]
=== 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.

[source,clojure]
----
(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.

[source,clojure]
----
(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.
