如何检查它是否是完整数据

时间:2022-11-08 16:09:53

I have a server that is receiving data from a client device. The client will send data to server and it always end up 3 characters, e.g. *46.

我有一台从客户端设备接收数据的服务器。客户端将数据发送到服务器,它总是最多3个字符,例如* 46。

How can I check if the data ends with an asterisk and 2 characters, so that I will know that this is the complete data from my client?

如何检查数据是否以星号和2个字符结尾,以便我知道这是来自客户端的完整数据?

Furthermore, the device may append a newline at the end of thedata, so how do I also check if there is newline at the end of data?

此外,设备可能会在数据的末尾添加换行符,那么我该如何检查数据末尾是否有换行符?

Here is my code so far:

到目前为止,这是我的代码:

var net = require('net');

var server = net.createServer(function(socket) {
   socket.on('data', function(data) {
       var receivedata = data.toString();
      // How to check if received data is complete, i.e. ending in 3 characters, *23
   });
});

3 个解决方案

#1


Use RegEx. For an example :

使用RegEx。举个例子:

var str = "Hello wor*23";
if(str.match(/\*[0-9][0-9]$/)){
  console.log("Hello");
}
else{
  console.log("Data not proper");
}

It checks if the last 3 values are * number number.

它检查最后3个值是否为*编号。

#2


You can use regular expressions for this. Here are a couple of links to help start you off:

您可以使用正则表达式。以下是一些帮助您启动的链接:

The actual regex expression you'll want is: *[0-9]{2}$

你想要的实际正则表达式是:* [0-9] {2} $

#3


You might be looking for this

你可能正在寻找这个

As long as the data is a chunk of a stream, you need to wait for the end event to get the complete data

只要数据是流的一部分,您就需要等待结束事件才能获得完整的数据

var net = require('net');

var server = net.createServer(function(socket) {
   var receivedata = "";
   socket.on('data', function(data) {
      receivedata += data.toString();
   });
   socket.on('end', function() {
      console.log(receivedata);
   });
});

Note untested

#1


Use RegEx. For an example :

使用RegEx。举个例子:

var str = "Hello wor*23";
if(str.match(/\*[0-9][0-9]$/)){
  console.log("Hello");
}
else{
  console.log("Data not proper");
}

It checks if the last 3 values are * number number.

它检查最后3个值是否为*编号。

#2


You can use regular expressions for this. Here are a couple of links to help start you off:

您可以使用正则表达式。以下是一些帮助您启动的链接:

The actual regex expression you'll want is: *[0-9]{2}$

你想要的实际正则表达式是:* [0-9] {2} $

#3


You might be looking for this

你可能正在寻找这个

As long as the data is a chunk of a stream, you need to wait for the end event to get the complete data

只要数据是流的一部分,您就需要等待结束事件才能获得完整的数据

var net = require('net');

var server = net.createServer(function(socket) {
   var receivedata = "";
   socket.on('data', function(data) {
      receivedata += data.toString();
   });
   socket.on('end', function() {
      console.log(receivedata);
   });
});

Note untested