nodejs 网络客户端套接字重新连接

nodejs net client socket reconnect

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?");
});

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

我试过在关闭事件中使用 setTimeout,但是当套接字连接时,'connect' 事件被多次触发。

您可以通过以下方式在保持事件绑定的情况下实现重连:

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();