Server Send Event Example
How to start
yarn install
yarn start
- Goto:
http://localhost:3000/
and opendevTools
to view logs - Goto
http://localhost:3000/admin
to send push notification to clients
Main files
-
routes/index.js
- Handle events route
router.get("/events", cors(), (req, res) => {
- Handle events route
-
views/index.hbs
- Setup client
EventSource
- Need an EventSource polyfill:
public/javascripts/eventsource.js
fromhttps://github.com/Yaffle/EventSource/
- Listen to 3 events:
- Default event:
message
- Custom event:
event
- Custom event:
pushNotification
- Default event:
- Setup client
-
Send push notification to all clients
routes/admin.js
andviews/admin.hbs
- Handle admin page to send push notification to all connected clients
routes/index.js
:router.post("/pushNotification", function(req, res, next) {
- Send message to all connections
-
Send push notification to a client
- Create
EventSource
with a query string:views/hbs
:
const id = Date.now(); const evtSource = new EventSource(`/events?id="${id}"`);
routes/index.js
:
const id = req.query.id; connections[id] = { res};
- Create
https://github.com/rexxars/sse-channel
Use this library to handle some events such as: error
, connect
, disconnect
, retry
routes/channels.hbs
andviews/channels.hbs