Home   tech  

Server sent events with example

Server-Sent Events (SSE) is a standard describing how servers can initiate data transmission towards browser clients once an initial client connection has been established. It's part of the HTML5 specification and provides a simple way to send text data from the server to the client in real-time. Unlike WebSockets, SSEs are designed exclusively for client-side updates (server to client) over a single, long-lived HTTP connection, making it an excellent choice for scenarios where only unidirectional communication is required.

How Server-Sent Events Work

  1. Client Request: A client makes a standard HTTP request to a server with an accept header indicating it's expecting an "event stream" format.
  2. Server Response: The server responds, maintaining the connection open, and sends data prefixed with "data:" followed by a newline character. Each message is separated by two newline characters.
  3. Client Handling: The client listens for these messages and acts upon them, typically updating the UI in real-time.

Advantages of SSE

Example

Here's a basic example demonstrating how to set up SSE on both the server (using Node.js) and the client side.

Server Side (Node.js)

Assuming you have Node.js installed, you can use the express framework for simplicity.

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/events', function(req, res) {
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    // Function to send a message
    const sendEvent = (data, id) => {
        res.write(`id: ${id}\n`);
        res.write(`data: ${JSON.stringify(data)}\n\n`); // Send a JSON object as a string
    };

    let messageId = 0;

    // Send an event every second
    const intervalId = setInterval(() => {
        sendEvent({ message: `Message ${++messageId}` }, messageId);
    }, 1000);

    // Clear interval on client disconnect
    req.on('close', () => {
        clearInterval(intervalId);
    });
});

app.listen(PORT, () => {
    console.log(`SSE server running on http://localhost:${PORT}`);
});

Client Side (HTML + JavaScript)

Create an HTML file and include the following JavaScript code to connect to the SSE endpoint and display messages.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Example</title>
</head>
<body>
    <h1>Server-Sent Events Example</h1>
    <div id="messages"></div>

    <script>
        const evtSource = new EventSource('/events');
        const messages = document.getElementById('messages');

        evtSource.onmessage = function(event) {
            const newElement = document.createElement("div");
            const eventObj = JSON.parse(event.data);

            newElement.textContent = "Message: " + eventObj.message;
            messages.appendChild(newElement);
        };
    </script>
</body>
</html>

Running the Example

  1. Run the Node.js server script.
  2. Open the HTML file in a browser, or serve it through the same or another server.
  3. You should see real-time messages appearing on the page, streamed from the server.
Published on: Feb 26, 2024, 12:00 AM  
 

Comments

Add your comment