Monday, 8 May 2017

Parsing JSON in socket.on Node.js

I'm sending data from Intel Edison which is in JSON format to a TCP server which is suppose to, for now just print the data on the console. The code for the TCP server:

var tempCallback = null;
var temp = ' ';

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

console.log('Connection from: ' + socket.remoteAddress);

socket.setTimeout(10000, function() {
    socket.end();
    socket.destroy();


});


socket.on('data', function getData(data){
    //if(data.toString().match(/temp\d{4}/)){

        //var temp = parseFloat(data.toString().split('=')[1].trim());
        temp += data;
        //console.log(temp);

        //db.saveTemp(new Date().getTime(),temp);
        var now = new Date();
        date.format(now, 'DD/MM/YYYY HH:mm');

        //db.saveTemp(now, temp);
        //console.log(now);
        //tempCallback(temp);
    /*}
    else {
        console.log('No match');
    }*/


});


socket.on('end', function(){
    var obj = JSON.parse(temp);
    console.log("Temperature = " + obj.temp);
    tempCallback(obj.temp);
    //temp = ' ';

});

});

My question is, is it possible to parse JSON as it comes in? From my understanding the connection has to end before I can parse the whole thing, but the data from Edison will be coming it constantly so the connection will have to be open all the time. Can someone help me understand it? Thanks



via Username

No comments:

Post a Comment