Node.js,Express和WebSockets:将消息中继到发件人以外的所有客户端

时间:2018-07-20 09:58:48

标签: 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", ... }(因为发件人不需要浏览器通知)。

1 个答案:

答案 0 :(得分:1)

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

希望这会有所帮助!