Server-Sent Events middleware
npm install --save @dropb/sse-channels
const { SseChannels } = require('@dropb/sse-channels');
const express = require('express');
const { join } = require('path');
const app = express();
app.get('/', (req, res) => {
res.sendFile(join(`${__dirname}/index.html`));
});
const sse = new SseChannels();
sse.on('connected', (client) => {
sse.send('message', `+++ ${client.req.query.ch} connected`);
});
sse.on('disconnected', (client) => {
sse.send('message', `--- ${client.req.query.ch} disconnected`);
});
app.use('/stream', (req, res) => {
sse.subscribe(req, res, req.query.ch);
});
setInterval(() => {
sse.channels.forEach((ch) => {
sse.publish(ch, `data: ${Math.random().toFixed(4)} channels: ${sse.channels.length} clients: ${sse.connections.length}`);
});
}, 3000);
app.listen(3005);
Available options are:
retryInterval
(integer): set clients reconnencting time. Default:1000
pingInterval
(integer): ping interval to keep connection alive. Default:10000
attach to HTTP request
channel
(string): assignchannel
drop client
send events to channels.
publish(eventObject: SseEvent): void;
publish(data: any): void;
publish(channels: string | string[] | RegExp, eventObject: SseEvent): void;
publish(channels: string | string[] | RegExp, data: any): void;
publish(channels: string | string[] | RegExp, event: string, data: any): void;
send events to clients.
eventName
(string): event name. Default:message
data
: event dataclients
(array) clients list
clients list filtered by channel
channel
(string | string[] | RegExp)