我已经安装了节点/表达式/ 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 - Node.js,Express和WebSockets:将消息中继到发件人以外的所有客户端,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51439992/

10-11 09:02