在 Node.JS 中向客户发送通知

Sending notification to clients in Node.JS

在 Node JS 应用程序中,我希望我的服务器能够在某些特定情况下向客户端发送通知。在网上搜索这个主题,我发现 Service Workers 似乎是我需要的;但我不是很确定。

原因如下。当我查看各种教程和视频时,通知似乎总是有点来自某些客户端。但这不是我想要的。应该由服务器决定何时以及发送什么作为通知,而不是某个客户端。我的问题来了:

  1. 我是不是误解了Service Worker的使用方式?
  2. 这是让我的服务器向客户端发送通知的正确路径吗?

如果最后一个问题的答案是否定的。那么正确的做法是什么?

答案是WebSockets

查看 Socket.IO。它将使您有可能在客户端接收实时通知,并且您将对它们拥有完整的服务器控制权。

如何使用 twilio 库来管理您的通知作业。twilio library

就像 Dimitar 之前写的那样,您可以使用 socket.io 从服务器向客户端发送消息,反之亦然。这可以这么简单地完成:

//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);
  });

websocket API 比 socket.io 更容易混淆,但在我看来,我会选择 socket.io,因为它已经处理了很多繁重的工作,比如重新连接、自定义命名空间、房间等。socket.io.

上有几门很棒的 udemy 课程

在此处查看 socket.io 文档:https://socket.io/docs/

2020 年 5 月 9 日更新:

Michel - 由于您询问了如何在您的代码中实现 Socket.io,我将举例说明我如何在我最近的项目中实现该技术。我正在开发一个连接到 ELK Alarm systems 并且能够 arm/disarm 这些系统以及在任何远程位置接收传感器输入(铃声信号)的网络应用程序。后端是 Node.js,UI 是 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.
                    } 
            })

我试图简化上面的代码来切中要点。服务器正在使用它从客户端接收到的连接参数来连接到远程报警系统。然后服务器等待并使用 client.on()(事件发射器 - 而不是 socket.io)侦听传入数据。收到数据后,我使用 Socket.io 通过 socket.emit(); 将接收到的数据发送回客户端;由于警报系统工作方式的性质,数据是事件驱动的,因此 fetch api 不符合要求,但 socket.io(或 websockets)符合要求。

如果我能帮上什么忙,请告诉我。在这个最近的项目中,过去几个月我一直在广泛处理 socket.io,包括名称空间、房间等。我还必须使用 socket.io 为我的服务器创建一个实时监控应用程序以进行性能管理因为我实施了集群。欢迎随时与我联系!