[英]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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.