javascript - How to wait on the data from net.socket to be fully submitted -
i need receive big json string windows application. can't seem figure out how need wait on data transmitted before close connection.
i've read need wait on callback, i've looked through documentation , can't wrap head around it.
i'm new node.js , javascript programming in general bear me here.
client.on('data', function(data) { completedata = data; //close connection client.end(); }); client.on('end', function() { //parse data after receiving full json responsedata = json.parse(completedata); console.log('received data \r\n' + json.stringify(responsedata, null, 4)); client.destroy(); console.log('connection closed'); next(); });
edit:
i've tried it's still closes before data.
client.on('data', function (data) { if (newlineregex.test(data)) { console.log('received: ' + data); responsedata = json.parse(data); console.log('received data \r\n' + json.stringify(responsedata, null, 4)); client.end(); }
});
edit: adding full code, must missing something. if add doesn't work code executes json.parse fast, if doesn't parse @ (doesn't end in client.on('end'))
var keystone = require('keystone'); var serverconnection = require('server-connection') var newlineregex = require('newline-regex'); exports = module.exports = function (req, res) { var view = new keystone.view(req, res); var locals = res.locals; // locals.section used set selected // item in header navigation. locals.section = 'server'; locals.responsedata = new object; var completedata; var net = require('net'); var client = new net.socket('null', true); client.connect(3333, '192.168.56.1', function (err) { console.log('connected'); //string test var string = '{"method":"getserialiseddeviceinfo","params":[],"id":1}\r\n'; client.write(string); }); client.on('data', function (data) { completedata = completedata + data; console.log(completedata); //doesn't work //if (newlineregex.test(completedata)) { //client.end(); //} }); client.on('end', function () { //parse data after receiving full json responsedata = json.parse(completedata); console.log('received data \r\n' + json.stringify(responsedata, null, 4)); client.end(); console.log('connection closed'); view.render('server'); }); };
there needs kind of established protocol determine end of "message" because tcp connections streams. there no built-in "message" boundaries have udp packets example.
in case of json, 1 popular , easy solution problem use newline-delimited json strings. way, need continually buffer data until see newline, know you've reached end of json message , can safely parse @ point.
Comments
Post a Comment