html_sse

Overview

Traditionally, client sends a request to the server to retrieve data; that is, client requests data from the server. With server-sent events(SSE), it’s possible for a server to send new data to client at any time, but only server can send message, one way communication.

Client with http GET method to setup a connection(keep it), server accepts it and keeps the connection as well, later on server sends event to client by this connection, when server sends event, the event is as TCP payload, not http, no http at all for event sending.

SSE is useful for stock price update, message notification. but new way is to use websocket for server event

The message(must be UTF-8 encoded when sending by server) has below fields, each takes one line when sending.

  • event(optional)
    A string identifying the type of event described. If this is specified, an event will be dispatched on the browser to the listener for the specified event name; the website source code should use addEventListener() to listen for named events. The onmessage handler is called if no event name is specified for a message.
  • data(optional), can be text or json format. can be multiple such field
    The data field for the message. When the EventSource receives multiple consecutive lines that begin with data:, it concatenates them, inserting a newline character between each one. Trailing newlines are removed.
  • id
    The event ID to set the EventSource object’s last event ID value.

but on client side, you got the parsed data, an object with below fields mapping to these fields, the name may be different

Client Side

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// open a connection and keep it, if disconnect, browser will reconnect automatically.
const evtSource = new EventSource("/events");

//only handle event:"ping", data is always a string(text, json format)
evtSource.addEventListener("ping", function(event) {
const newElement = document.createElement("li");
const time = JSON.parse(event.data).time;
newElement.innerHTML = "ping at " + time;
eventList.appendChild(newElement);
});

// handle message without type
evtSource.onmessage = function(event) {
const newElement = document.createElement("li");
const eventList = document.getElementById("list");

newElement.innerHTML = "message: " + event.data;
eventList.appendChild(newElement);
}

evtSource.onerror = function(err) {
// such as a network timeout or issues pertaining to access control
console.error("EventSource failed:", err);
};

Server Side(JS)

Events sent by server

1
data: some text
1
2
data: another message
data: with two lines
1
2
type: userconnect
data: {"username": "bobby", "time": "02:33:48"}
1
2
3
4
5
6
7
8
9
10
11
// $yarn add express-sse
sse.js
var express = require('express');
var router = express.Router();

var SSE = require('express-sse');
var sse = new SSE();
router.get('/events', sse.init);

//you can see sse in any other file
module.exports = router;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var sse = require('./sse').sse;
let count = 0;
setInterval(() => {
// sse.send(content)
// sse.send(content, eventName);
// sse.send(content, eventName, customID);

//send message to all connections!!!!
//if no sse connection, it does not send at all
sse.send('jason');
sse.send('jason', 'name');
sse.send(100);
sse.send({name: "jason"}, 'name');
}, 10000);