Sse-example - SSE (server-sent events) example using Node.js

Overview

sse-example

SSE (server-sent events) example using Node.js

SSE is a easy way to commutate with the client side in a single direction. it has loss cost and efficiency way compared to other protocols like Socket or polling query.

Here is a minium checklist to create a SSE service:

Server Side

  1. response three HTTP headers that tell the client that the response is a SSE stream:

    • Connection: keep-alive
    • Content-Type: text/event-stream
    • Cache-Control: no-cache
  2. response data with data , event and id attributes

  3. That's all

Client Side

  1. create a EventSource object

  2. addEventListener to the EventSource object

  3. That's all


There is a simple example to show how to create a SSE service using Node.js.

Installation

Install dependencies before running example.

$ yarn

Start

$ yarn start // start client
$ yarn run server // start server

After run command above, you can open http://localhost:1234 see the result in the browser.

Server

The server is a simple Node.js application that listens on port 3000. I create a Server Sent Event while sends data to the client interval in one second. Here is the core core of the server.

ctx.set({
  // necessary HTTP Headers for server sent events
  Connection: "keep-alive",
  "Content-Type": "text/event-stream",
  "Cache-Control": "no-cache",

  // CORS settings
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Credentials": "true",
});

const pipe = new stream.PassThrough();
// normalize message without event name specified
pipe.write(`id: ${Math.random()}\ndata: hello from steam\n\n`);

const interval = setInterval(() => {
  // normalize message with event name(eg:currentTime) specified
  pipe.write(`id: ${Math.random()}\nevent: currentTime\ndata: ${new Date().toUTCString()}\n\n`);
}, 1000);

ctx.body = pipe;

// clear interval and destroy stream object while client disconnect
ctx.res.on("close", () => {
  clearInterval(interval);
  pipe.destroy();
});

Client

In the client side, it's easy to create a event source to listen on the server. the EventSource object return a readable stream which you can addEventListener by open, message and error event. Also, you can create custom event listeners by addEventListener method. see example below:

const source = new EventSource(API, {
  withCredentials: true,
});

source.addEventListener("open", (e: Event) => {
  console.log("event source is open");
});

// event name not specified, message is default
source.addEventListener("message", (e: MessageEvent) => {
  console.log("'message' event received:", e.data);
});

// event name(eg:currentTime) specified
source.addEventListener("currentTime", (e: any) => {
  console.log("'currentTime' event received:", e.data);
});

source.addEventListener("error", (e: Event) => {
  console.error("event source error", e);
  source.close();
});

Enjoy Hacking!

You might also like...

A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Dec 30, 2022

μWebSockets for Node.js back-ends :metal:

μWebSockets for Node.js back-ends :metal:

Simple, secure[1] & standards compliant[2] web server for the most demanding[3] of applications. Read more... A note on NPM drama ⚡ Simple performance

Jan 8, 2023

JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript

WebSockets for Node.js and JavaScript/TypeScript with JSON RPC 2.0 support on top. About The rpc-websockets library enables developers to easily imple

Dec 21, 2022

ONG-Node JS

Server Base - Proyecto ONG Envinroment setup Create database Copy .env.example to .env and fill with database credentials.

Dec 30, 2021

Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js

CHAT-APP-WEBSOCKET Mini Projeto de um chat-app usando o protocolo WebSocket através da lib 'ws' do node.js Obs o intuito deste projeto não é o fronten

Jul 14, 2022

Unix dgram, seqpacket, etc binding for Node.js.

Unix dgram, seqpacket, etc binding for Node.js.

node-unix-socket node-unix-socket allows you to use some nonblocking unix sockets that are currently not supported by Node.js native modules, includin

Dec 27, 2022

Lightweight WebSocketServer wrapper lib using ws-wrapper to wrap connected WebSockets

ws-server-wrapper Lightweight WebSocketServer wrapper lib using ws-wrapper and ws to wrap connected WebSockets. The only dependency is ws-wrapper itse

May 9, 2022

Create a Real-time Chat App using React and Socket.io

React And Socket.io ChatApp MIT Licence MIT License Copyright (c) 2021 Ali Ahmad Permission is hereby granted, free of charge, to any person obtaining

Jan 10, 2022

How to build a chat using Lambda + WebSocket + API Gateway? (nodejs)

How to build a chat using Lambda + WebSocket + API Gateway? (nodejs)

Description Source code for the lambda function from the screencast How to build a chat using Lambda + WebSocket + API Gateway? (nodejs) The reactjs c

Dec 28, 2022
Owner
Jack
Saving the world!
Jack
A node.js module for websocket server and client

Nodejs Websocket A nodejs module for websocket server and client How to use it Install with npm install nodejs-websocket or put all files in a folder

Guilherme Souza 719 Dec 13, 2022
WebSocket emulation - Node.js server

SockJS-node SockJS for enterprise Available as part of the Tidelift Subscription. The maintainers of SockJS and thousands of other packages are workin

SockJS 2.1k Dec 29, 2022
Simple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js

ws: a Node.js WebSocket library ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation. Passes the quit

WebSockets 19.2k Jan 4, 2023
This Repository implements an Authenticated Websocket Server built in Node Js along ws library.

websockets-authentication-server This Repository implements an Authenticated Websocket Server built in Node Js along ws library. Features Authenticate

M.Abdullah Ch 7 May 5, 2023
An example about web socket with .net 3.1 and react

Websocket Example This is a real time app example which is using web socket, dot net core and react. Project Case You are a factory manager and you ha

Samet Yazıcı 5 Jan 11, 2022
Standards-compliant WebSocket client and server

faye-websocket This is a general-purpose WebSocket implementation extracted from the Faye project. It provides classes for easily building WebSocket s

null 588 Dec 23, 2022
Super-Resolution-CNN - web server for super-resolution CNN

Web Server for Image Super-Resolution This project showcases the Super-Resolution CNN (SRCNN). The model is pretrained following this tutorial. The or

Daniel O'Sullivan 1 Jan 3, 2022
soketi is your simple, fast, and resilient open-source WebSockets server

soketi soketi is your simple, fast, and resilient open-source WebSockets server. ?? Blazing fast speed ⚡ The server is built on top of uWebSockets.js

Soketi 3.2k Jan 4, 2023
This server is made to serve the MSN-Messenger app develop by Gabriel Godoy. This applications is capable to register users and messages in order implements a real time chat.

?? MSN-Messenger-Server Node.js server for real time chat About | Installations | How to Use | Documentation | Technologies | License ?? About This se

Guilherme Feitosa 7 Dec 20, 2022
🚀🚀🚀 Nuxt3 client and server communication

Nuxt 3 Minimal Starter Look at the nuxt 3 documentation to learn more. Setup Make sure to install the dependencies: # yarn yarn install # npm npm ins

HomWang 4 Dec 19, 2022