Database Reference
In-Depth Information
Connection: keepalive
Transfer-Encoding: chunked
event:alpha
id:1234
retry:10000
data:{"hello":"world"}
id:12345
data:{"again":"and again"}
This response returns a simple one-line message with an
id
of 1234 and
sets the retry time from 30 seconds to 10 seconds. To read this message,
supporting browsers use the
EventSource
class. This class fires an event
corresponding to the event name given in the response. If no event is
specified, the object fires a
message
event.
To modify the example dashboard application to respond, the server fires
counter events to transmit a JSON object containing updates to each
counter.
First, the application must establish a connection to the server. This is
mostly handled by the
EventSource
object, which takes a URL to the SSE
connection. In this case, the connection lives at
/api/v1/dashboard
and
is implemented in
dashboard/public/javascripts/sse.js
:
$(document).ready(function() {
var events = new EventSource('/api/v1/dashboard');
The
EventSource
object emits a number of events besides the messaging
events described earlier. Handling those events is optional, but it often
provides useful debugging information. The most important events are the
open
and
error
events, which are called when the event stream is
successfully established and when the event stream is closed, or another
error event occurs (such as a 500). In this simple example, these events
simply report being called to the console for debugging purposes:
events.addEventListener('open',function(e) {
if(window.console) console.log("opened SSE
connection");
});
events.addEventListener('error',function(e) {