使用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
答案 0 :(得分: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);
希望这适合你!
答案 1 :(得分: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.writable
为undefined
,因此永远不会发送emit
事件。在连接时将属性设置为true
,并在关闭时将其设置为false
。