LIVE UPDATES WITH
JavaScript community
Wait, Vue ?
46 % developers want to learn it, but didn't try
Server-Sent Events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP/2 (HTTP/1.1) connection.
Server Sent Events
Is this a WebSocket ?
The server receives a regular HTTP request from the client.
Every time that the server writes an event to the HTTP response, the client will receive it and process it in a listener callback function
The client creates a new JavaScript EventSource object, passing it the URL of an endpoint which is expected to return a stream of events over time.
SSE is unidirectional. When you open a SSE connection, only the server can send data to the client (browser, etc.). The client cannot send any data.
To enable servers to push data to Web pages over HTTP or using dedicated server-push protocols, this specification introduces the EventSource interface.
created() {
const receiveMessage = this.receiveMessage;
const eventSource = new EventSource("http://localhost:3000/event-stream");
eventSource.onmessage = function(event) {
console.log("New message", event.data);
receiveMessage(JSON.parse(event.data));
};
}
Note: event.data is a string, so we need to parse it and convert to object
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.get('*', (req, res) => res.send('OK'));
app.get('/sse', (req, res) => {
// create SSE connection
});
app.listen(3000, () => console.log('server started...'));
app.get('/sse', (req, res) => {
// SSE Setup
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
});
res.write('\n');
let messageId = 0;
const intervalId = setInterval(() => {
res.write(`id: ${messageId}\n`);
res.write(`data: Test Message -- ${Date.now()}\n\n`);
messageId += 1;
}, 1000);
req.on('close', () => {
clearInterval(intervalId);
});
});
function createConnections() {
let list = [];
return {
send(message) {
messageId++;
list.forEach(({ id, req, res }) => {
console.log('Sending for: ', id)
res.write(`id: ${messageId}\n`);
res.write(`data: ${JSON.stringify(message)}\n\n`);
});
},
add(id, req, res) {
list.push({ id, req, res })
},
remove(id) {
list = list.filter(item => item.id !== id);
}
}
}
Link to slides: