4

使用 node.js,我试图server_time每秒向所有客户端发送电流。因此,我想用它setInterval()来向所有客户端发出事件并发送时间,但它不起作用。我是setInterval在正确的地方定义了函数还是错过了其他东西?

var http = require("http");
var socketIO = require('socket.io');
var connect = require('connect');

//keep track of every connected client
var clients = {};

//create Server 
var httpServer = connect.createServer(
    connect.static(__dirname)
).listen(8888);


//socket
var io = socketIO.listen(httpServer);
io.sockets.on('connection', function (socket) {

    //add current client id to array
    clients[socket.id] = socket;
    socket.on('close', function() {
        delete clients[socket.fd]; // remove the client.
    });

    //send news on connection to client
    socket.emit('news', { hello: 'world' }); 

    //this one works fine!
    //send server time on connection to client
    socket.emit("server_time", { time: new Date().toString() });

});

//this doesn't work!
// Write the time to all clients every second.
setInterval(function() { 
    var i, sock;
    for (i in clients) {
        sock = clients[i];
        if (sock.writable) { // in case it closed while we are iterating.
            sock.emit("server_time", {
                console.log("server_time sended");
                time: new Date().toString()

            });
        }
    }
}, 1000);       //every second
4

2 回答 2

2

我可以建议一个解决问题的解决方法/改进。将客户添加到聊天室。在某处:

io.sockets.on('connection', function (socket) {

添加一个

socket.join('timer');

那么 setIntervall 将是

setInterval(function() { 
    io.sockets.in('timer').emit("server_time", { time: new Date().toString() })
}, 1000); 

希望这对你有用!

于 2012-10-08T17:24:52.627 回答
2

问题是以下功能:

if (sock.writable) { // in case it closed while we are iterating.
  sock.emit("server_time", {
    // console.log("server_time sended"); // get rid of this line -> invalid code
    time: new Date().toString()
  });
}

sock.writableundefined,因此该emit事件永远不会发送。将属性设置为trueon connection 和falseon close。

于 2012-10-08T18:02:24.953 回答