gpt4 book ai didi

node.js - nodejs tcp 监听器脚本

转载 作者:可可西里 更新时间:2023-11-01 02:54:38 30 4
gpt4 key购买 nike

我有以下情况,只是想检查一下我是否做对了。我的客户有几个设备 (RS232)。现在我有一个 RS232-WIFI 加密狗与之连接,因此设备外的数据被发送到我的服务器(它输出一个数据字符串,例如:{12,1,etc)。在我的服务器上,我运行了一个 NodeJS 脚本,它打开一个端口并获取所有传入的数据。

var net = require('net');
var host = '1.1.1.1';
var servers = [];
var ports = [20000, 20001, 20002, 20003, 20004];

// Create servers
ports.forEach(function (port) {

var s = net.createServer(function (sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED (' + sock.localPort + '): ' + sock.remoteAddress + ':' + sock.remotePort);

// Add a 'data' event handler to this instance of socket
sock.on('data', function (data) {
// post data to a server so it can be saved and stuff
postData(data.toString(), sock);

// close connection
sock.end();
});

sock.on('error', function (error) {
console.log('******* ERROR ' + error + ' *******');

// close connection
sock.end();
});
});

s.listen(port, host, function () {
console.log('Server listening on ' + host + ':' + s.address().port);
});

servers.push(s);
});

好的,所以这很好用。但我想知道,有时并非所有数据都一次发布,有时我得到 {12, ,一秒钟后我得到其余的(甚至需要更多次)。我可以做些什么来进一步优化这个脚本?收到数据后需要调用sock.end();吗?这会影响我或我的客户的网络性能吗?如果你们需要更多信息,请告诉我。

最佳答案

这取决于你的设备的协议(protocol),如果设备使用每个连接来处理一大块数据,你可以这样编写程序:(不要在数据事件上关闭套接字)

....
// socket will close and destroy automatically after the device close the connection
var s = net.createServer(function (sock) {
sock.setEncoding('utf8');

var body = "";
sock.on('data', function (data) {
body = body + data;
});

sock.on('end', function() {
console.log(data);
postData(data);
});

// TODO error handling here
});
....

注意:Socket 不能保证一次给你所有数据,你应该在使用前监听数据事件然后连接所有 block 。

如果你的设备没有关闭socket,你将不会收到on('end'),那么代码应该是这样的:

....
var s = net.createServer(function (sock) {
sock.setEncoding('utf8');

// var body = "";
sock.on('data', function (data) {
// body = body + data;
postData(data);
});

sock.on('end', function() {
console.log('end');
});

// TODO error handling here
});
....

关于node.js - nodejs tcp 监听器脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20911083/

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