簡體   English   中英

node.js setInterval不起作用

[英]node.js setInterval doesn't work

使用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

我可以建議一個解決方法/改進,以解決問題。 將客戶端添加到聊天室 在某處:

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

添加一個

socket.join('timer');

那么setIntervall就是

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

希望這對你有用!

問題是以下功能:

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.writable undefined ,因此從不發送emit事件。 在連接時將屬性設置為true ,在關閉時將屬性設置為false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM