trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Server Sent Events (SSE) #23

Open trasherdk opened 5 months ago

trasherdk commented 5 months ago

Docs: SSEventStream

Version using HyperExpress

const HyperExpress = require("hyper-express");

const server = new HyperExpress.Server();

server.get("/sse", (request, response) => {
    if (response.sse) {
        console.log("client got connected");
        response.once("close", () => {
            console.log("client got disconnected");
        });

        response.sse.open();
        response.sse.send("sse connection open");

        setInterval(() => {
            response.sse.send("event sent");
        }, 5000);
    } else {
        response.send("SSE not supported");
    }
});

server.listen(3000, () => console.log("Listening on port 3000"));

Version using Express

const express = require("express");

const app = express();

app.get("/sse", (request, response) => {
    console.log("client got connected");
    request.on("close", () => {
        console.log("client got disconnected");
    });

    // setting up SSE manually
    response.writeHead(200, {
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
        "Connection": "keep-alive",
    });
    response.write(`data: sse connection open\n\n`);

    setInterval(() => {
        response.write("data: event sent\n\n");
    }, 5000);
});

app.listen(3000, () => console.log("Listening on port 3000"));