0

我有一个正在运行的 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 数据。

但是我从哪里开始呢?

4

1 回答 1

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来自客户端,并被服务器监听。

于 2013-09-05T16:22:54.693 回答