我需要连续的数据接收。但是我尝试了setinterval()但没有成功。然后我尝试了setinterval()也没有成功,我在发送消息后收到第一个响应,没有成功,请您帮帮我。 这是输出; [在此处输入图像描述] [1]
var HOST = '202.71.103.XXX';
var PORT = XXXX;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
setInterval(getData, 1000);
});
function getData() {
console.log('fun called')
client.on('data', function(data) {
console.log('Get Data: ' + data)
Cdata = JSON.parse(data.slice(0, -2))
if (Cdata.ServerDist == 1) {
var sentMsg = '{"ClientID":"' + Cdata.ClientID + '","TrackSystemNos":"13992881XXX|"}';
client.write(sentMsg)
console.log('Sent Msg: ' + sentMsg)
}
});
}
[1]: https://i.stack.imgur.com/7Mt0Y.png
答案 0 :(得分:0)
好的,所以我不是100%知道您的特定问题是什么,但是我根据您的代码编写了一个简单的客户端和服务器,它工作得很好,所以看看是否有帮助。
服务器:
const net = require('net');
var dummy = {
ServerDist: 1
};
var server = net.createServer(function(socket) {
let temp = JSON.stringify(dummy)
console.log(temp);
socket.write(temp);
socket.on('data', data => {
let temp = JSON.stringify(dummy);
console.log(temp);
socket.write(temp);
});
});
server.listen(1337, '127.0.0.1');
客户
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 1337;
var client = new net.Socket();
client.connect(PORT, HOST, function () {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('init');
});
client.on('data', function (data) {
console.log('Get Data: ' + data);
let Cdata = JSON.parse(data);
if (Cdata.ServerDist === 1) {
let sentMsg = {ClientID: 'Bob', TrackSystemNos: '13992881XXX'};
client.write(JSON.stringify(sentMsg));
console.log('Sent Msg: ' + JSON.stringify(sentMsg))
}
}
);
输出:
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
Get Data: {"ServerDist":1}
Sent Msg: {"ClientID":"Bob","TrackSystemNos":"13992881XXX"}
旧答案 我相信您的问题是setinterval是异步调用。因此,只要您调用它,代码就会从connect函数中继续出来(很可能会终止连接)。 setinterval之所以会获得第一个响应,是因为它在关闭之前就已存在于调用中,但由于连接已关闭,因此不再有响应。
您是否尝试过在连接内部使用while循环以保持连接打开?