处理Node.js套接字数据

Che*_*lix 5 javascript sockets string networking node.js

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

这样做:

console.log(data)
Run Code Online (Sandbox Code Playgroud)

我明白了

<Buffer d0 d7 3d 00 c4 56 7e 81>
Run Code Online (Sandbox Code Playgroud)

也试过了

 console.log(data.toString())
Run Code Online (Sandbox Code Playgroud)

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

??A?V~?
Run Code Online (Sandbox Code Playgroud)

这是我的完整代码:

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);
Run Code Online (Sandbox Code Playgroud)

感谢您的输入.

小智 9

根据文档,您必须指定一个编码来获取String而不是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().
Run Code Online (Sandbox Code Playgroud)

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

socket.setEncoding('utf8');
Run Code Online (Sandbox Code Playgroud)


小智 1

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

console.log(data.toString('ascii'))
Run Code Online (Sandbox Code Playgroud)

将解决问题。