简体   繁体   English

Express JS中的Socket.io在连接上执行多次

[英]Socket.io in Express JS on connection execute multiple times

I refer this repo to integrate socket.io. 我引用此仓库来集成socket.io。

What I want to achieve is, a countdown timer, which send to client every second, setInterval is run on server side. 我要实现的是一个倒数计时器,该计时器每秒钟发送到客户端一次, setInterval在服务器端运行。 The result I get is 我得到的结果是

Socket.io和Express JS

The terminal there is on.('connection') , first time I refresh the page, it executed 4 times on.('connection') , the countdown is working fine. 终端on.('connection') ,我第一次刷新页面时,它执行了4次on.('connection') ,倒计时工作正常。 Then I refresh 2nd time, it executed 8 times on.('connection') , and the countdown timer also have 2 values there. 然后我第二次刷新,它执行了8次on.('connection') ,并且倒数计时器在那里也有2个值。 Then continue.... 12 times, 16 times... 然后继续... 12次16次

In app.js app.js中

app.use(function(req, res, next){
  res.io = io; 
  io.on('connection', function(socket) {
    console.log(socket.id + ' connected.');
  }); 
  next();
});

In routes/users.js routes / users.js中

router.get('/', function(req, res, next) {

  models.User.findAll({
    include: [ {model: models.Task, as: 'tasks'} ]
  }).then(function(users) {

    var eventTime= new Date('2017-03-31 13:00:00').getTime();
    var currentTime = new Date().getTime();
    var diffTime = eventTime - currentTime;
    var duration = moment.duration(diffTime*1000, 'milliseconds');
    var interval = 1000;

    setInterval(function() {
      duration = moment.duration(duration - interval, 'milliseconds');
      res.io.emit('countdown', { time_left: duration.hours() + ":" + duration.minutes() + ":" + duration.seconds() }); 
    }, interval);

    res.render('users', {
      title: 'Sequelize: Express Example',
      users: users
    });   
  });   
});

Anything goes wrong here? 这里有什么问题吗?

I found the answer here 我在这里找到答案

io.on('connection', function(socket) {
  socket.removeAllListeners(); <---------- ADD THIS LINE
  console.log(socket.id + ' connected.');
}); 

I think you probably your keeping io.on('connection') event within setInterval. 我认为您可能在setInterval中保持了io.on('connection')事件。 That's why it every time keeps on replication in *2. 这就是为什么它每次都在* 2中保持复制。

You can do it like this if you want to achieve countdown timer : 如果要实现倒数计时器,可以这样操作:

io.on('connection', function (socket){
  var tick = 0;
  setInterval(function(){

    socket.emit('timer', tick++)
  }, 1000);
}) 

Now you can listen to timer event on front-end and display result. 现在,您可以在前端监听timer事件并显示结果。 Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM