nodejs net client socket重新连接

时间:2016-10-09 09:12:05

标签: javascript node.js sockets client

var socket = new net.Socket();
socket.connect(PORT, HOST, function() {
    console.log("SOCKET CONNECTED TO: " + HOST + ":" + PORT);
    socket.write("Hello World!");
});
socket.on("error", function() {}); // need this line so it wont throw exception

// Add a "close" event handler for the client socket
socket.on("close", function() {
    console.log("Connection lost. How do I reconnect? setTimeout?");
});

失败后如何重新连接?现在如果连接不成功,一切都会停止..

我尝试在close事件中使用setTimeout,但是当套接字连接时,'connect'事件被多次触发..

1 个答案:

答案 0 :(得分:0)

您可以在保持事件绑定的同时以下列方式重新连接:

function connect() {
    var socket = new net.Socket();
        socket.connect(PORT, HOST, function() {
            console.log('SCOEKT CONNECTED TO: ' + HOST + ':' + PORT);
            socket.write('Hello World!');
        });

    socket.on('error', function() {}); // need this line so it wont throw exception

    // Add a 'close' event handler for the client socket
    socket.on('close', function() {
        connect();
    });
}
connect();