nodejs JSON.parse(数据_来自_TCP_socket) [英] nodejs JSON.parse(data_from_TCP_socket)

查看:518
本文介绍了nodejs JSON.parse(数据_来自_TCP_socket)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用require('net')的nodejs服务器上有此代码,因此它是TCP,客户端是AS3并正确发送数据:

I have this code at nodejs server that is working with require('net'), so it is TCP, client side is AS3 and sending data correctly:

var server = net.createServer(function(socket) {

    socket.setEncoding("utf8");
    clients.push(socket);   

    function broadcast(message) {
        clients.forEach(function (client) {
            client.write(message);
        });
    }

    socket.on('data', function(dt){
        var rdt = dt;
        var srdt = rdt.toString();
        var ordt = JSON.parse(srdt);
        console.log(ordt);
        broadcast(ordt);
    }); 

    socket.on('end', function(){...});
})

它无法解析数据并给出各种错误.我能理解的是,我从客户端获得了缓冲".但是我需要保持套接字打开状态,因此使用循环缓冲区的常见解决方案对我不起作用.

It can not parse the data and give all kinds of errors. The thing I could understand that I get "buffer" from the client. But I need to keep sockets opened, so common solutions with looping buffer won't work for me.

请帮助我解决这个问题.

Please help me to solve this.

BTW,对数据进行字符串化的客户端,当它在发送时收到数据时,会对其进行正确解析.

BTW, client that stringifies the data, when receives this data back as it was sent, parses it correctly.

推荐答案

ValRus是正确的;您需要使用substring(0,str.length-1)删除最后一个字符.

ValRus is correct; you need the substring(0, str.length-1) to remove the last char.

  let str = reading.toString('utf8');
  console.log( "String = %s", str );
  let obj = JSON.parse( str.substring(0, str.length-1) );


  let str2 = JSON.stringify(obj, null, 4); // Reverse conversion
  console.log("Obj = %s", str2);           // and output to inspect

这是我从MQTT消息缓冲区中提取JSON所需的代码.

This is the code I needed to pull JSON out of an MQTT message buffer.

(而且使用Java或C进行调试会变得非常容易-很好的主意是Javascript很痛苦!)

(And this would have been sooooo much easier to debug in Java or C - good Lord is Javascript a pain!)

这篇关于nodejs JSON.parse(数据_来自_TCP_socket)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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