WebSocket 断开连接时如何重新连接? [英] How to reconnect when a WebSocket disconnects?

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

问题描述

示例:

var WebSocket = require('ws');
var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
ws.on('open', function() {
    console.log('connected');
    ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function() {
    console.log('disconnected');
    // What do I do here to reconnect?
});

socket关闭后重新连接服务器怎么办?

What should I do when the socket closes to reconnect to the server?

推荐答案

您可以将所有设置包装在一个函数中,然后从关闭处理程序中调用它:

You can wrap all your setup in a function and then call it from the close handler:

var WebSocket = require('ws');
var openWebSocket = function() {
    var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
    ws.on('open', function() {
        console.log('connected');
        ws.send(Date.now().toString(), {mask: true});
    });
    ws.on('close', function() {
        console.log('disconnected');
        openWebSocket();
    });
}
openWebSocket();

然而,您可能需要更多的逻辑(如果 close 是故意的呢?如果您在重新连接时尝试发送消息会发生什么?).你可能最好使用图书馆.aembke 在评论中建议的 这个库 似乎是合理的.socket.io 不是一个糟糕的选择(它为您提供非 WebSocket 传输).

However, there is likely more logic you want here (what if the close was on purpose? what happens if you try to send a message while its reconnecting?). You're probably better off using a library. This library suggested by aembke in the comments seems reasonable. socket.io is not a bad choice (and it gives you non-WebSocket transports).

这篇关于WebSocket 断开连接时如何重新连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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