javascript 处理 Node.js 套接字数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21851424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:49:54  来源:igfitidea点击:

Handling Node.js socket data

javascriptstringnode.jssocketsnetworking

提问by Cheruiyot Felix

I have server receiving data from a client [GPS Device]. I have problem presenting the data (i.e the results obtained from the client) in a readable format. Below are the things I have tried.

我有服务器从客户端 [GPS 设备] 接收数据。我在以可读格式呈现数据(即从客户端获得的结果)时遇到问题。以下是我尝试过的事情。

Doing:

正在做:

console.log(data)

I get

我得到

<Buffer d0 d7 3d 00 c4 56 7e 81>

Also tried

也试过

 console.log(data.toString())

But I get unwanted results:See below:

但我得到了不需要的结果:见下文:

??A?V~?

Here is my full code:

这是我的完整代码:

var net = require('net');
var fs = require('fs');

var server = net.createServer(function (socket) {
  console.log('Server started: Waiting for client connection ...');
  console.log('Client connected:port,address: '+socket.remotePort,      socket.remoteAddress);
  socket.on('data', function (data) {
        var date = new Date();
        var today = date.getDate()+'_'+date.getMonth();
        fs.appendFile(today+'_log.txt', data, function (err) {
          if (err) throw err;
            console.log(data.toString())

    });
 });
});

server.listen(my_port, my_ip);

Thanks for your input.

感谢您的输入。

回答by combefis

According to the documentation, you must specify an encoding to get a String instead of a Buffer:

根据文档,您必须指定编码才能获取字符串而不是缓冲区:

Event: 'data'#
Buffer object
Emitted when data is received. The argument data will be a Buffer or String. Encoding of data is set by socket.setEncoding().

You could configure the socket to get the data in UTF-8, for example, with:

您可以配置套接字以获取 UTF-8 格式的数据,例如:

socket.setEncoding('utf8');

回答by Cheruiyot Felix

Assuming the data in buffer is 7 bit ASCII,

假设缓冲区中的数据是 7 位 ASCII,

console.log(data.toString('ascii'))

would resolve the problem.

将解决问题。