WebSocket:如何在它死后自动重新连接 [英] WebSocket: How to automatically reconnect after it dies

查看:2101
本文介绍了WebSocket:如何在它死后自动重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function () {
  ws.send(JSON.stringify({
      .... some message the I must send when I connect ....
  }));

};

ws.onmessage = function (e) {
  console.log('Got a message')
  console.log(e.data);
};

ws.onclose = function(e) {  
  console.log('socket closed try again'); 

}

ws.onerror = function(err) {
  console.error(err)
};

当我第一次连接到套接字时,我必须首先向服务器发送一条消息来验证自己和订阅频道。

When I first connect to the socket, I must first send a message to the server to authenticate myself and subscribe to channels.

我遇到的问题是套接字服务器有时不可靠并触发 onerror onclose 'ws'对象的事件。

The problem I have is that sometimes the socket server is unreliable and that triggers the onerror and onclose events of the 'ws' object.

问题:什么是一个好的设计模式,允许我,无论何时套接字关闭或遇到错误,等待10秒然后重新连接到套接字服务器(和将初始消息重新发送到服务器)

Question: What is a good design pattern that would allow me, whenever the socket closes or encounters an error, wait for 10 seconds and then reconnect to the socket server (and resend the initial message to the server)

推荐答案

这是我最终的结果。它适用于我的目的。

Here is what I ended up with. It works for my purposes.

function connect() {
  var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function() {
    // subscribe to some channels
    ws.send(JSON.stringify({
        //.... some message the I must send when I connect ....
    }));
  };

  ws.onmessage = function(e) {
    console.log('Message:', e.data);
  };

  ws.onclose = function(e) {
    console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
    setTimeout(function() {
      connect();
    }, 1000);
  };

  ws.onerror = function(err) {
    console.error('Socket encountered error: ', err.message, 'Closing socket');
    ws.close();
  };
}

connect();

这篇关于WebSocket:如何在它死后自动重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆