【问题标题】:Node.js - WebSocket only works when refreshing the pageNode.js - WebSocket 仅在刷新页面时有效
【发布时间】:2020-01-23 18:23:59
【问题描述】:

我正在尝试与 Node.js 中的 websocket 进行通信。它在第一次打开页面时工作,但如果不稍后刷新页面,我就无法接收消息。

HTML 页面 WEBSOCKET 代码:

var ws ;

function init() {
   ws = new WebSocket('ws://localhost:40510');

    ws.onopen = function () {
       ws.send('test')
    }

     ws.onmessage = function (ev) {
      console.log(ev)
    }
 }

  window.addEventListener("load", init, false);

服务器端代码:

app.get('/sayfayiYenile', function (req, res) {
 wss.on('connection', function connection(ws) {
    ws.send('abc');
  });
  res.end('test')
});

Chrome 控制台:

MessageEvent {isTrusted: true, data: "abc", origin: "ws://localhost:40510", lastEventId: "", source: null, …}

当我按下按钮时,它进入服务器端的“/sayfayiYenile”发布方法,但不发送消息。然后我刷新 HTML 页面并发送消息。

【问题讨论】:

    标签: javascript node.js websocket socket.io connection


    【解决方案1】:

    您的 .get 方法没有发出消息,而是包装了 .on("connection") websocket 逻辑。您应该将ws.on 功能放在.get 之外,并实现将消息发送到特定连接的逻辑。

    例子:

    const connections = [];
    
    wss.on('connection', function connection(ws) {
      ws.send("Welcome...");
    
      // Store the list of connections for later use
      connections.push(ws);
    });
    
    app.get('/sayfayiYenile', function (req, res) {
      // Iterate over the current connected clients and send a message
      // @todo implement logic here to filter out specific connections
      connections.forEach(function(connection) {
        connection.send('abc');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 2017-01-20
      • 2013-12-13
      • 1970-01-01
      • 2018-01-15
      • 1970-01-01
      • 2012-10-23
      • 2016-11-02
      相关资源
      最近更新 更多