javascript - Nodejs、Express 和 WebSockets : Relaying a message to all clients other than the sender

标签 javascript node.js express websocket

我已经使用以下代码启动并运行了一个 node/express/ws 服务器

'use strict';
var http = require('http');
var https = require('https');
var fs= require('fs');
var express = require('express');
var WebSocket = require('ws');

var server = {
    cert: fs.readFileSync('../ssl/wss/new/certificate.pem'),
    key: fs.readFileSync('../ssl/wss/new/private.pem'),
    ca: fs.readFileSync('../ssl/wss/new/ca_bundle.pem'),
    rejectUnauthorized: false
};

var web = express();

//Server initializations
var httpServer = http.createServer(web);
var httpsServer = https.createServer(server, web);
var wss = new WebSocket.Server({ server: httpsServer });
httpServer.listen(8080);
httpsServer.listen(58443, function listen(connection) {});

我有以下监听客户端发送的事件

wss.broadcast = function broadcast(data) {
    wss.clients.forEach(function each(client) {
        if (client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(data) {
        if(JSON.parse(data)) {
            data = JSON.parse(data+'\n');
            if(data.proto == "SN_NOTI") { //Want to send to everyone that's not the sender.
                var mes = {
                    type: 'NOTI',
                    title: data.title,
                    body: data.body
                }
                wss.broadcast(JSON.stringify(mes));
            } else if (data.proto == "UP_NOTI") { //Send to everyone, including sender
                var msg = {type: "UP_NOTI"}
                wss.broadcast(JSON.stringify(msg));
            } else if (data.proto == "msg") {
                console.log(data.value);
            }
        } else {
            console.log("Had some trouble.");
        }
    });
});

我想做的是发送消息 var = mes { type: "NOTI", ... } 给除发件人以外的所有其他客户端(因为发件人不需要浏览器通知)。

最佳答案

.broadcast 方法向所有人发送消息,因此您需要像这样使用.on(connection) 方法,

此处 client !== ws 条件排除了发送者。

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(data);
      }
    });
  });
});

希望这对您有所帮助!

关于javascript - Nodejs、Express 和 WebSockets : Relaying a message to all clients other than the sender,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439992/

相关文章:

javascript - 退出javascript函数不起作用

javascript - Visual Studio 单页应用程序集成

javascript - Node.js、Express.js 不向客户端发送文件

javascript - PyBossa 加载和呈现任务

javascript - 如何使用 lodash、underscore 或 bluebird 同步迭代数组

node.js - Mocha - 哪个先运行,beforeEach 还是 before?

flash - Nodejs、Socket.io 和 Flash 中的套接字

javascript - 使用 Node.js 和 MySQL 进行连续数据库插入(已将握手排队后无法将握手排队)

javascript - Heroku 服务器上出现 H12 和 503 错误

javascript - 如何将 React 应用程序部署到运行 NodeJS 的共享主机?