gpt4 book ai didi

javascript - Nodejs - 让客户端套接字在 5 秒超时后重试

转载 作者:搜寻专家 更新时间:2023-11-01 00:11:13 24 4
gpt4 key购买 nike

刚开始使用 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 秒。有更好的想法吗?

最佳答案

你的超时被逆转了。

应该看起来像:

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) {
if(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 the 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');
});

超时后要运行的函数是回调。那就是等待执行的那个。

此外,将您的 while 更改为 if,该条件在单个错误事件期间不会更改。你的括号和括号不匹配。

关于javascript - Nodejs - 让客户端套接字在 5 秒超时后重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19981040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com