2012-10-08 7 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

setInterval 함수의 맨 위에 console.log를 넣으십시오 (var i, sock; 위). 나는 당신이 클라이언트의 배열이 비어 있거나 소켓이 쓰기 가능하지 않다는 것을 알게 될 것입니다. – PherricOxide

답변

2

이 문제를 해결할 수있는 대안/개선 방법을 제안 할 수 있습니다. chat room에 클라이언트를 추가하십시오. 어딘가에서 :

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

그런 다음 setIntervall이 당신을 위해 작동

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

희망이 될 것

socket.join('timer'); 

를 추가!

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 이벤트가 전송되지 않습니다 :

2

문제는 다음과 같은 기능입니다. 연결시 속성을 true으로 설정하고 닫으면 false으로 설정하십시오.

관련 문제