HTML and CSS Reference
In-Depth Information
The server needs to keep the connection open to the client,
and it must send the client a header with the mime type
text/event-stream .
The server needs to send new messages as such:
id: 1\n
data: { “semiment”: “like”, “time”: “2011-06-23 16:43:23”
¬ }\n\n
Two new lines indicate the end of the message. If we were
sending just plain sentences (rather than JSON in Bruce's case),
the API supports sending multiple lines as such:
data: Here's my first really, really, really long line,
¬ but -\n
data: I've not just finished there, I've got more to
¬ say.\n\n
data: Since I follow two blank lines, I'm an entirely new
¬ message\n\n
In the example above, only two messages would be sent. Also
notice that I'm not using any IDs either—they're not mandatory,
but if you want to support the picking up where you dropped off
feature, you'll want to include the IDs.
A simple EventSource server
What follows is some very simple Node.js code to accept con-
nections to an EventSource -based server and send messages.
Again, it's beyond the scope of this topic to explain the server
logic, but it should give you a starting point. I've also simplified
the solution so the server just notifies connected users about
the user agent string of other visitors that are currently con-
nected to the same service. We'll keep Bruce's special toy chart-
ing experiment for another day!
/** When they create a new Event Source */
response.writeHead(200, {'Content-Type':
¬ 'text/event-stream', 'Cache-Control': 'no-cache'});
// get the last event id and coerce to a number
var lastId = req.headers['last-event-id']*1;
if (lastId) {
for (var i = lastId; i < eventId; i++) {
response.write('data: ' + JSON.stringify
¬ (history[eventId]) + '\nid: ' + eventId + '\n\n');
Search WWH ::

Custom Search