刚开始使用 node.js 编程并编写一个 tcp 套接字客户端。
我希望客户端连接到服务器。如果服务器不可用(即服务器在约定的端口上不存在),我希望客户端超时并在超时后重新连接。
我有这段代码,但它挂在第二个 client.connect 上。怎么了?
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9000;
var client = new net.Socket();
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Superman!');
});
client.on('error', function(e) {
while (e.code == 'ECONNREFUSED') {
console.log('Is the server running at ' + PORT + '?');`
socket.setTimeout(1000, function() {
console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
}
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am the inner superman');
});
});
});
更新代码:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 9000;
var client = new net.Socket();
client.connect(PORT, HOST, function(){
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am Superman');
});
client.on('error', function(e) {
while (e.code == 'ECONNREFUSED') {
console.log('Is the server running at ' + PORT + '?');
client.setTimeout(4000, function() {
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('I am inner Superman');
});
console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
});
}
});
client.on('data', function(data) {
console.log('DATA: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
使用更新的代码,超时似乎没有生效。当我在没有相应服务器的情况下启动此客户端时,结果显示如下,无需等待 4 秒。
Is the server running at 9000?
Is the server running at 9000?
Is the server running at 9000?
Is the server running at 9000?
…
更新(吠叫错误的树?)
我回去查看 socket.on('error') 事件,发现错误发生后立即调用了 close 事件。所以代码将关闭 tcpclient 而无需等待 4 秒。有更好的想法吗?