简体   繁体   English

尽管收到了来自服务器的消息,但 Chrome 的 onmessage() 不会在重新连接后立即触发

[英]Chrome's onmessage() does not fire immediately after reconnect, despite receiving a message from the server

I'm currently trying to create a websocket between chrome and a NodeJS server.我目前正在尝试在 chrome 和 NodeJS 服务器之间创建 websocket。 The Node server is using the ws plugin, and I'm using Chrome's default websocket handler. Node 服务器使用的是ws插件,我使用的是 Chrome 的默认 websocket 处理程序。

Here are my lines of code for the server:这是我的服务器代码行:

wss.on('connection', function connection(ws) {
  ws.id = uuid();
  let response = {'type': 'uuid','data': ws.id};
  ws.send(JSON.stringify(response));
});

And my code for the client:我的客户代码:

//Listens for new messages
connection.onmessage = function(e) {
  let data = JSON.parse(e.data);
  console.log(data.data);
}

What I expect: The server generates a UUID for the client everytime they create a connection, and the client prints it to console.我的期望:服务器每次创建连接时都会为客户端生成一个 UUID,然后客户端将其打印到控制台。 When the connection is severed and the client reconnects, the server sends a new UUID to the client.当连接被切断并且客户端重新连接时,服务器会向客户端发送一个新的 UUID。

What happens: The server generates a UUID for the client when they create a connection, and the client prints it to console.发生了什么:服务器在创建连接时为客户端生成一个 UUID,客户端将其打印到控制台。 However, when the server goes down and comes back up, and the client re-establishes a connection, the server does send a new UUID to the client, but chrome just isn't picking it up.但是,当服务器关闭并重新启动,并且客户端重新建立连接时,服务器确实会向客户端发送一个新的 UUID,但 chrome 只是没有接收到它。

Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks!谢谢!

Edit: This is how I reconnect to the server编辑:这就是我重新连接到服务器的方式

//Reconnect to server
setInterval(function() {
  if (connection.readyState !== WebSocket.OPEN) {
    reconnect = false;
    connection.close();
    console.log("Disconnected from server. Retrying...");
    connection = new WebSocket(server);
  } else {
    if (!reconnect) {
        reconnect = true;
        console.log("Reconnected to server.");
    }
  }
}, 1000);

Edit 2: Modified the code, still doesn't work:编辑2:修改了代码,还是不行:

//Webhook
//On connection open
connection.onopen = function() {
  console.log("Connected to server");
  reconnect = "";
  //Reconnect to server if disconnected
  connection.onclose = function(e) {
    console.log("Connection closed, reconnecting...");
    //Retry every second
    reconnect = setInterval(function() {
        if (connection.readyState !== WebSocket.OPEN) {
            connection.close();
            console.log("Connecting to server...");
            connection = new WebSocket(server);
        }
    }, 1000);
  }
}

onopen() does not fire on reconnections either, so the client will try to reconnect every second after disconnecting, and will never stop. onopen()也不会在重新连接时触发,因此客户端将在断开连接后每秒尝试重新连接,并且永远不会停止。

I found a solution我找到了解决方案

//Webhook
function connect() {
  //Attempt to connect to server
  if (firstConnect) {
    console.log("Connecting to server...");
    connection = new WebSocket(server);
  } else {
    if (connection.readyState !== WebSocket.OPEN) {
      connection.close();
      console.log("Connecting to server...");
      connection = new WebSocket(server);
    }
  }

  //On connection open
  connection.onopen = function() {
    firstConnect = false;
    console.log("Connected to server");
    clearInterval(reconnect);
  }

  //Listens for new messages
  connection.onmessage = function(e) {

 }

   //Reconnect to server if disconnected
   connection.onclose = function(e) {
    console.log("Connection closed, reconnecting...");
    connect();
  }
}

When you create a new socket connection, chrome will repeatedly try to connect on its own until it times out.当您创建新的套接字连接时,chrome 会反复尝试自行连接,直到超时。 Timing out will fire connection.onclose , which in turns calls connect() .超时将触发connection.onclose ,进而调用connect()

By nesting it all in connect() , the event handlers will be hooked onto the new websocket connection everytime.通过将其全部嵌套在connect()中,事件处理程序将每次都挂接到新的 websocket 连接上。 Furthermore, you will not need to setInterval() , thus avoiding any performance issues.此外,您不需要setInterval() ,从而避免任何性能问题。

Browsers tested on: Chrome, Opera, Safari测试的浏览器:Chrome、Opera、Safari

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 新标签页上的Chrome.runtime.onMessage.addListener未从popup.js接收消息 - Chrome.runtime.onMessage.addListener on new tab not receiving message from popup.js 制作 chrome 扩展和 chrome.runtime.onMessage 没有收到消息 - Making chrome extension and chrome.runtime.onMessage isn't receiving the message 尽管从服务器接收到消息,但未调用信号 R 客户端事件处理程序 - Signal R client event handler not invoked despite receiving message from server 如何仅在收到服务器的回复消息后才显示 DIV? - How to show DIV only after receiving reply message from server? 使用Java服务器甚至无法触发onmessage - javascript - onmessage even will not fire using a java server 客户端未从服务器接收消息 - Client not receiving message from server 为什么我的Chrome扩展程序内容脚本的运行时没有任何onMessage仅连接和发送消息 - Why does the runtime of my Chrome extension content script not have any onMessage only connect and send message 为什么Firefox和Chrome的Unload事件在初始获取时或回发后会触发? - Why does Firefox and Chrome's Unload event fire on initial get or after a postback? Chrome.runtime.onMessage无法将消息从弹出窗口发送到内容脚本 - Chrome.runtime.onMessage doesn't work to send message from popup to content script 服务器发送事件EventStream不会触发“onmessage”,但Chrome Debug会在“EventStream”选项卡中显示数据 - Server sent event EventStream does not trigger “onmessage” but Chrome Debug shows data in “EventStream” tab
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM