如何在服务器重启时重新连接

如何在服务器重启时重新连接

本文介绍了NodeJS Websocket 如何在服务器重启时重新连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Node.js 中,我使用 websockets/ws 进行 WebSocket 连接.下面是客户端的代码.假设我们要连接的服务器套接字关闭一分钟.close 事件将触发,但是当服务器上的套接字出现故障或错误时重新连接到套接字的最佳方法是什么?

In Node.js I'm using websockets/ws for a WebSocket connection. Below is the code for the client. Let's say the server socket we are connecting to goes down for a minute. The close event will fire, but what is the best way to reconnect to the socket whenever the socket on the server goes down or errors?

var ws = new WebSocket('ws://localhost');

ws.on('open', function() {
    console.log('socket open');
});
ws.on('error', function() {
    console.log('socket error');
    // how do I reconnect to the ws after x minutes here?
});
ws.on('close', function() {
    console.log('socket close');
    // how do I reconnect to the ws after x minutes here?
});

推荐答案

我用过 https://github.com/joewalnes/reconnecting-websocket/blob/master/reconnecting-websocket.js 成功.

你应该能够做到:

ws = new ReconnectingWebSocket('ws://....');
ws.reconnectInterval = 60000; // try to reconnect after 10 seconds

这篇关于NodeJS Websocket 如何在服务器重启时重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 08:09