2012-10-08 115 views
3

使用node.js,我试图在每秒钟将所有客户端发送当前的server_time。 因此,我想用setInterval()向所有客户发送一个事件并发送时间,但它不起作用。我是否在正确的地方定义了setInterval函数,或者错过了其他的东西?node.js 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 
+0

它不起作用的方式?有没有错误或消息是不是发出? –

+0

如果你删除'console.log(“server_time sended”);'? – halex

+0

把一个console.log放在你的setInterval函数的最上面(上面的var i,sock;)。我想你会发现它被调用的很好,但是你的客户端数组是空的或者套接字是不可写的。 – PherricOxide

回答

2

我可以提出一个应该解决问题的解决方法/改进方案。将客户添加到chat room。某处:

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

添加

socket.join('timer'); 

然后setIntervall将

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

希望这对你的作品!

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事件。关闭时将该物业设置为true,并将其设置为false