ServerSideEvents (SSE)

JS
S
JavaScript

If your application primarily requires server-to-client updates and simplicity is a priority, EventSource (SSE) might be a better choice. However, if you need bi-directional communication or more control and flexibility, WebSockets would be a better fit. Server-Sent Events (SSE) can be considered relatively reliable even with poor connections. SSE uses HTTP, which is built on top of the TCP protocol. TCP ensures that data is delivered reliably by retransmitting lost or corrupted packets and reordering out-of-order packets.

1// Server.js
2const express = require('express');
3const app = express();
4const cors = require('cors');
5
6app.use(cors());
7
8// Route to handle SSE
9app.get('/events', (req, res) => {
10  res.setHeader('Content-Type', 'text/event-stream');
11  res.setHeader('Cache-Control', 'no-cache');
12  res.setHeader('Connection', 'keep-alive');
13  res.flushHeaders();
14
15  // Send an event every second
16  let counter = 0;
17  setInterval(() => {
18    res.write(`data: ${counter}\n\n`);
19    counter++;
20  }, 1000);
21
22  // Close the connection when the client disconnects
23  req.on('close', () => {
24    res.end();
25  });
26});
27
28const PORT = process.env.PORT || 3000;
29app.listen(PORT, () => {
30  console.log(`Server running on port ${PORT}`);
31});
32
33
34// =================================================================================
35// index.html
36<!DOCTYPE html>
37<html lang="en">
38<head>
39  <meta charset="UTF-8">
40  <title>SSE Example</title>
41</head>
42<body>
43  <h1>SSE Example</h1>
44  <div id="sse-data"></div>
45
46  <script>
47    const sseDataElement = document.getElementById('sse-data');
48
49    // Connect to the SSE endpoint on the server
50    const source = new EventSource('http://localhost:3000/events');
51
52    // Listen for messages from the server
53    source.onmessage = (event) => {
54      sseDataElement.textContent = `Server says: ${event.data}`;
55    };
56
57    // Handle errors
58    source.onerror = (error) => {
59      console.error('SSE connection error:', error);
60      source.close();
61    };
62  </script>
63</body>
64</html>
65

Created on 4/15/2023