socket.on仅在页面重新加载后触发

时间:2016-07-06 13:50:06

标签: events socket.io

我的客户端socket.on在调用服务器后没有触发(socket.emit('callserver')。但是,当我刷新页面时,它工作正常!我不确定我是否理解这一点。任何想法为什么情况如此?感谢任何输入!

这是我的客户代码:

  socket.on('pauseTimeClock', function (data) {
    stopWatchClock.setPausedTime(data.time);
    $('.pauseTime').html(data.time.replace(/(\d)/g, '<span>$1</span>'))
    console.log(stopWatchClock.pausedTime);
});

this.pause = function (stopwatch) {
        this.stopwatch = stopwatch;

        socket.emit('pauseTime');

        this.stopwatch.changeState(this.stopwatch.getPauseState());

    }

在服务器上:

socket.on('pauseTime', function () {
//stop broadcasting countDown time
clearInterval(timeinterval);

var pausedTime = moment();

function pauseTimeClock() {

  var timeDiffHour = moment().hour() - pausedTime.hour();
  var timeDiffMinute = moment().minute() - pausedTime.minute();
  var timeDiffSec = moment().second();

  var displayTime = timeDiffHour + ":" + timeDiffMinute + ":" + timeDiffSec;

  socket.broadcast.emit("pauseTimeClock", { time: moment(displayTime, 'hhmm').format('HH:mm') });

}

setInterval(pauseTimeClock, 1000);

})

1 个答案:

答案 0 :(得分:0)

在我周围搜索之后,我发现socket.broadcast.emit向除了新创建的客户端之外的所有客户端广播,而socket.emit向所有人广播。