简体   繁体   中英

Sending notification to clients in Node.JS

In a Node JS app, I want my server to be able to send a notification to clients, in some specific cases. Searching the net on the subject, I find Service Workers which seems to be what I need; but I am not totally sure.

Here is why. When I look at various tutorials and videos, it seems like the notifications always somewhat originates from some client. But this is not what I want. It should be the server deciding when and what to send as a notification, not some client. So comes my questions:

  1. Am I misunderstanding the way to use Service Workers?
  2. Is this the right path to have my server send a notification to clients?

If the answer to the last question is NO. Then what is the proper way?

The answer is WebSockets .

Check out Socket.IO . It will give you the possibility of receiving live notifications on the client and you'll have complete server control on them.

Like Dimitar wrote earlier, you could use socket.io to send messages from the server to the client and vice versa. This can be done as simple as that:

//Server sent message:
io.on('connection', (socket) => {
  socket.emit('notificationToClient', 'Message'); //message sent from server to client 
  });
});

//Client receives the message:
const socket = io.connect('http://localhost:3000');
  socket.on('notificationToClient', (data) => { //received message 
    console.log(data);
  });

The websocket API is a little less confusing than socket.io but IMO, I'd go with socket.io since it already deals with a lot of the heavy lifting like re-connecting, custom namespaces, rooms etc. There are several fantastic udemy courses on socket.io.

See the socket.io documentation here: https://socket.io/docs/

Update 5/9/2020:

Michel - Since you asked about how to implement Socket.io in your code I'll give you an example of how I implemented this technology in my most recent project. I was working on a web app that connects to ELK Alarm systems and is able to arm/disarm these systems as well as receive sensor input (chime signals) at any remote location. The backend is Node.js and the UI is React.

//client side code

import React, { Component, Suspense } from 'react';
import panels from "./panels.js"

const socketConnection = io("http://localhost:5000"); //Socket.io

function App() {

    function handleClick(panel) {
        socketConnection.emit("panelData", panel); //Socket.io - sends the connection data for the ELK alarm panel to the express server

        socketConnection.on('data', (data) => { //Socket.io - receives data from the server.
         //does something with the data
        })
    }
}

//server side code

const express = require('express');
const elkClient = require('elk-client');

const app = express();

const server = app.listen('5000', () => {
  console.log('------Server Running on 5000---------');
});

let io = new sio(server);

io.on("connection", (socket) => { //boilerplate code - establishes the "handshake" with the client.
 
    socket.on("panelData", async (msg) => { //receives the ELK connection parameters from the client. See client side code
    const client = new ElkClient({
                connection: { 
                  site: msg.name,
                  host: msg.host,
                }
              })
        await client.connect();

    client.on("message", (elkMessage) => { // This is NOT Socket.io - server is listening for emitted data from the alarm system - beam breaks, alarms, arm/disarm etc. [See event emitter][2]
                    if(elkMessage.messageType == 'A' && elkMessage.subMessageType == 'S') {
                      const armingStatusReport = {elkMessage};
                      socket.emit("data", armingStatusReport); //Socket.io - emits the received data to the client.
                    } 
            })

I tried to simplify the code above to hit the point. The server is using the connection parameters that it receives from the client to connect to a remote alarm system. The server then waits and listens for incoming data with client.on()(event emitter - not socket.io). As the data is received, I'm using Socket.io to send the received data back to the client with socket.emit(); Due to the nature of how alarm systems work, data is sent event driven so the fetch api wouldn't really fit the bill but socket.io (or websockets) does.

Let me know if I can help with anything else. With this recent project, I have spent the last few months EXTENSIVELY dealing with socket.io, including namespaces, rooms etc. I also had to create a real-time monitoring app for performance management for my server utilizing socket.io since I implemented clustering. Feel free to contact me anytime!

What about using twilio library to manage your notification job. twilio library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM