NodeJS Websocket如何在服务器重新启动时重新连接 [英] NodeJS Websocket how to reconnect when server restarts

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

问题描述

在Node.js中,我使用 https://github.com/einaros/ws 一个WebSocket连接。以下是客户端的代码。假设我们连接的服务器套接字下降了一分钟。关闭事件将触发,但是当服务器上的套接字发生故障或错误时,重新连接到插座的最佳方式是什么?

In Node.js I'm using https://github.com/einaros/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如何在服务器重新启动时重新连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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