我的使用ExpressJS的NodeJS Web应用程序正在从Android应用程序接收数据。接收数据后,我们正在通过TCP / IP套接字流将数据发送到另一台服务器。一切工作正常,但是由于数据以非常快的速度发送,因此服务器拒绝了某些事务的连接。我们需要在API调用或Socket编写之间创建延迟,以使连接不会被拒绝。这是我的代码
function send(data, tr_id, server_ip, port) {
var client = new net.Socket();
client.connect(port, server_ip, function () {
try {
console.log('Connected');
client.write(data);
} catch (error) {
console.log("Send function error " + error);
}
});
client.on('data', function (data) {
console.log('Received: ' + data);
//set the flag 1 in tbl_transactions
if (data.includes("status='ACK'")) {
dbConn.query("UPDATE tbl_transaction set flag='1' where tr_id =" + tr_id, function (err, rows, fields) {
if (err)
console.log('error occured in updating flag - ' + err.code + " ,error_description - " + err);
});
}
client.destroy(); // kill client after server's response
});
client.on('close', function () {
console.log('Connection closed');
});
client.on('error', function (error) {clearImmediate
console.log(error);
});
}
我尝试过使用计时器,但无法使用其他任何可靠的解决方案吗?
答案 0 :(得分:0)
您可以使用promise和setTimeout创建睡眠功能:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
答案 1 :(得分:0)
将setTimeout包装在更新查询周围,延迟1秒:
setTimeout(function(){
dbConn.query("UPDATE tbl_transaction set flag='1' where tr_id =" + tr_id, function (err, rows, fields) {
if (err)
console.log('error occured in updating flag - ' + err.code + " ,error_description - " + err);
});
}, 1000);