【问题标题】:Websocket - browser websocket is not receiving messages from serverWebsocket - 浏览器 websocket 没有从服务器接收消息
【发布时间】:2017-08-15 14:38:56
【问题描述】:

我用 Node 构建了一个 websocket 服务器和客户端,两者都工作正常。但是,我在单个 html 页面上构建了一个客户端,当我从浏览器调用 sendUTF 时,websocket 正在监听消息。节点客户端发送的消息不能被浏览器客户端读取。这是一个安全问题/功能还是我很愚蠢?

服务器代码:

var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer( (req, res) => {
    console.log((new Date()) + ' Received request for ' + request.url);
    res.writeHead(404);
    res.end();
});

server.listen(8080, () => {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production 
    // applications, as it defeats all standard cross-origin protection 
    // facilities built into the protocol and the browser.  You should 
    // *always* verify the connection's origin and decide whether or not 
    // to accept it. 
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed. 
  return true;
}

wsServer.on('request', (request) => {
/*    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin 
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }*/

    var connection = {};
    try {
        connection = request.accept('echo-protocol', request.origin);
        console.log((new Date()) + ' Connection accepted.');
        connection.on('message', function(message) {
            if (message.type === 'utf8') {
                console.log('Received and send Message: ' + message.utf8Data);
                connection.sendUTF(message.utf8Data);
            }
            else if (message.type === 'binary') {
                console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
                connection.sendBytes(message.binaryData);
            }
            else {
                console.log('Received unknown format message: ' + message);
                connection.send(message);
            }
        });

        connection.on('close', function(reasonCode, description) {
            console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
        });        
    }
    catch(e) {
        console.error("Client fail trying to connect to websocket: " + e);
    }


});

节点客户端代码:

var express = require('express');
var app = express();
server = require('http').createServer(app);
var WebSocketClient = require('websocket').client;

var kinect = new Kinect2();

app.use(express.static(__dirname + 'js/View'));
//app.use(express.static(__dirname + 'js/Script'));

//instance of WebSocket object
var wsClient = new WebSocketClient();

//Websocket connection events
wsClient.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
    process.exit(0);
});

wsClient.on('connect',(connection) => {


    connection.on('error', (error) => {
      console.error("Connection Error: " + error.toString());
      process.exit(0);
    });

    connection.on('close',() => {
      console.log("Websocket connection is closed!");
    });

    // connection.on('message',(message) => {
    //   if (message.type === 'utf8') {
    //     console.log("Received: '" + message.utf8Data + "'");
    //   }
    // });
    console.log('Websocket connection OK!');

    setInterval(() => {
      console.log("sending message...");
      connection.send("This is a test!");
    },1000);
    //startKinect(connection);

});

wsClient.connect('ws://127.0.0.1:8080','echo-protocol');

终于我的浏览器客户端

<!DOCTYPE html>
<html>
<head>
    <title>
        Websocket test
    </title>                                                     
</head>
<body>
    <h1>Websocket client test</h1>

    <script>
        console.log("Open Websocket...");
        var websocket = new WebSocket('ws://127.0.0.1:8080','echo-protocol');

        websocket.onopen = function () {
          console.log("websocket was open");
          //websocket.send('Websocket is working(I gess)');
        };

        websocket.onclose = () => {
          console.log("Websocket was closed!");
        }

        websocket.onerror = (error) =>{
          console.error("Websocket error: " + JSON.stringify(error));
        };

        websocket.onmessage = (message) => {
          // Web Socket message:

            console.log("MSG: " + message.data );


        };

        websocket.addEventListener('message',(e) => {
          websocket.onmessage(e);
        })

    </script>

</body>
</html>

欢迎任何帮助!谢谢!

【问题讨论】:

  • 如果我理解正确,您是在尝试通过 WebSockets 从节点客户端到浏览器客户端进行通信?这是不可能的,因为 WebSockets 使用服务器在服务器和客户端之间进行双工通信,而不是客户端和客户端。但是,使用 WebSockets 进行 P2P 通信似乎有一些进步,可能会对您有所帮助:stackoverflow.com/questions/4118272/…
  • 不,不是那样的! websocket 有一个服务器和两个客户端。 nodejs 客户端是“生产者”并写入 websocket。浏览器客户端是“消费者”,它应该能够从 websocket 读取,除非我的概念是错误的。

标签: javascript node.js html websocket


【解决方案1】:

您的服务器作为回显工作(客户端 -> 服务器 -> 客户端),但您描述的是广播(客户端 -> 服务器 -> 客户端s)。您应该保留客户的参考,然后发送给所有客户。

request 事件处理程序之外,添加:

var connections = [];

接受请求后,将连接添加到数组中:

connections.push( connection );

然后当你想向所有人发送数据时,循环连接:

for ( var i = 0; i < connections.length; i++ )
    connections[ i ].sendUTF( message.utf8Data );

【讨论】:

  • 感谢您的回答!但是我不明白如果这个对象只是因为“请求”对象而存在(或者我不明白你写了什么),我怎么能在“请求”事件之外使用“连接”对象?请你解释一下好吗?
【解决方案2】:

看来我错过了“广播”部分。幸运的是,'ws' 模块让我可以非常轻松地做到这一点!

const WebSocket = require('ws');
var port = 8080;
const wss = new WebSocket.Server({ "port": port });

// Broadcast to all.
wss.broadcast = function broadcast(data) {
  wss.clients.forEach(function each(client) {
    if ( client.readyState == WebSocket.OPEN && data != undefined ) 
      client.send(data);
  });
};

wss.on('connection', function connection(ws) {
  console.log("CONNECTION OK...");
  ws.on('message', function incoming(data) {
    // Broadcast to everyone else.
    wss.broadcast(data);
  });
});

【讨论】:

    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多