javascript - How to only transmit data through websocket if different from previous transmission -
i have built simple web application using nodejs + express, request , socket.io modules json data external api , transmit using websocket client.
what transmit through websocket if externally requested json data has changed.
i cannot figure out how add condition code have come far:
io.on('connection', function (socket) { setinterval(function () { request({ url: url, json: true }, function (error, response, body) { var senddata = json.stringify(body.result).tolowercase(); if (!error && response.statuscode === 200) { socket.emit('result', senddata); } }) }, 3000) });
you can store last data each socket in object, compare senddata
:
var lastdata = {}; //declare object io.on('connection', function (socket) { setinterval(function () { request({ url: url, json: true }, function (error, response, body) { var senddata = json.stringify(body.result).tolowercase(); if (!error && response.statuscode === 200) { if (senddata !== lastdata[socket.id]) { //compare senddata last data lastdata[socket.id] = senddata; //store new last data socket.emit('result', senddata); } } }) }, 3000) });
hope helps.
Comments
Post a Comment