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, client that stringifies the data, when receives this data back as it was sent, parses it correctly.
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
This is the code I needed to pull JSON out of an MQTT message buffer.
(And this would have been sooooo much easier to debug in Java or C - good Lord is Javascript a pain!)