处理Node.js套接字数据 [英] Handling Node.js socket data

查看:115
本文介绍了处理Node.js套接字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

执行:

console.log(data)

我得到

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

还试过

 console.log(data.toString())

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

But I get unwanted results:See below:

��A�V~�

这是我的完整代码:

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);

感谢您的输入。

推荐答案

根据文档,您必须指定一个编码来获取String而不是Buffer:

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().

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

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

socket.setEncoding('utf8');

这篇关于处理Node.js套接字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆