【问题标题】:Nodejs, Express & WebSockets: Relaying a message to all clients other than the senderNodejs、Express 和 WebSockets:将消息中继到发送者以外的所有客户端
【发布时间】:2018-07-20 09:58:48
【问题描述】:

我已经使用以下代码启动并运行了一个 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", ... }(因为发件人不需要浏览器通知)。

【问题讨论】:

  • 查看socket.braodcast
  • 有一个错字,socket.broadcast 是:p
  • 我尝试过使用 socket.io,虽然我不是粉丝,因此将其排除在外。

标签: javascript node.js express websocket


【解决方案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);
      }
    });
  });
});

希望这会有所帮助!

【讨论】:

  • 效果很好!谢谢你:)
猜你喜欢
  • 2016-06-02
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 2023-04-01
相关资源
最近更新 更多