2013-09-05 25 views
0

我有一個socket.io連接與數據在socket.io

客戶

var socket = io.connect('http://localhost:8080'); 
    socket.on('news', function (data) { 
    console.log(data); 
    socket.emit('my other event', { my: 'data' }); 
    }); 

和服務器運行

var app = require('http').createServer(handler) 
, io = require('socket.io').listen(app) 
, fs = require('fs') 

var url = 'pathtojson'; 

app.listen(8080); 

function handler (req, res) { 
    fs.readFile(__dirname + '/index.html', function (err, data) { 
    if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'); 
    } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

io.sockets.on('connection', function (socket) { 
socket.emit('news', url); 
socket.on('my other event', function (data) { 
    console.log(data, 'server'); 
    }); 
}); 

這只是從socket.io爲例。我想要在客戶端更新時向客戶端發送json數據。

但我從哪裏開始?

回答

1

只要您有興趣更新的數據發生變化,您就需要觸發事件,然後您需要讓客戶端偵聽該事件並根據需要進行響應。

你真的不給比,所以假設你在任何過程中更新服務器上的JSON「每當它被更新JSON數據發送到客戶端」以外的情境:

if (req.url === '/endpoint') { 
    yourJSON.foo = 'bar'; 
    // doing whatever you're interested in to the JSON 
    socket.emit('JSON changed', yourJSON); 
    //an event is defined by the first argument, 
    //a value is passed with it as the second 
} 

注意:獲得更多花哨/體貼的意思是改變你的JSON,使得套接字只響應數據變化(事件,回調等)而發出。闡明這種模式可能超出了問題的範圍。

然後在客戶端上,要定義一個函數來處理這些變化:

socket.on('JSON changed', updateFunction); 
//where updateFunction is a function you define 
//that is expecting arguments that match the output 
//from the connected socket.emit event 

function updateFunction(newJSON) { 
    //do whatever with new JSON data 
} 

這是假設有被訪問的更新JSON一些外部端點;讓它通過socket.io來自客戶端,只需要定義另一個事件,但這次是從客戶端獲取emit,並由服務器監聽。