![](/img/trans.png)
[英]transmit xlsx data from php to javascript through json data structure
[英]How to only transmit data through websocket if different from previous transmission
我使用NodeJS + Express,request和socket.io模塊構建了一個簡單的Web應用程序,以從外部API獲取JSON數據,然后使用Websocket將其傳輸到客戶端。
我只想在外部請求的JSON數據已更改的情況下通過websocket進行傳輸。
我無法弄清楚如何用到目前為止我提出的代碼添加這種條件:
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)
});
您可以將每個套接字的最后數據存儲在一個對象中,然后將其與senddata
進行比較:
var lastData = {}; //declare an 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 with last data
lastData[socket.id] = senddata; //store new last data
socket.emit('result', senddata);
}
}
})
}, 3000)
});
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.