WebSocket断开连接时如何重新连接?

时间:2014-07-30 21:34:49

标签: node.js 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?
});

当套接字关闭以重新连接到服务器时,我该怎么办?

1 个答案:

答案 0 :(得分:0)

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

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在评论中提出的This library似乎是合理的。 socket.io不是一个糟糕的选择(并且它为您提供非WebSocket传输)。

相关问题