最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sending notification to clients in Node.JS - Stack Overflow

programmeradmin1浏览0评论

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 es 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?

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 es 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?

Share Improve this question asked May 8, 2020 at 10:11 MichelMichel 11.8k20 gold badges101 silver badges217 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 ining 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!

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 plete server control on them.

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

发布评论

评论列表(0)

  1. 暂无评论