socket.io不监听全局事件

时间:2018-09-02 10:14:19

标签: javascript sockets socket.io sails.js

我正在研究Socket.io文档,但仍然无法弄清为什么io.sockets.on无法正常工作。我尝试使用io.on,但没有成功。

在客户端上,我只是听事件socket.on(ROUND_START/ROUND_END)

此客户端侦听器正在工作,但是服务器一-io.sockets.on(ROUND_START...-无法工作。

服务器

/**
 * Handle  Game phases
 */
const NEXT_GAME_TIMEOUT = 5000;
const END_GAME_TIMEOUT = 10000;
const FULL_GAME_TIMEOUT = END_GAME_TIMEOUT + NEXT_GAME_TIMEOUT;
const ROUND_START = "ROUND_START";
const ROUND_END = "ROUND_END";

setInterval(() => {
  io.sockets.emit(ROUND_START);
}, FULL_GAME_TIMEOUT);

// Not working
io.sockets.on(ROUND_START, () => {
  console.log("ROUND STARTED")

  setTimeout(() => {
    io.sockets.emit(ROUND_END);
  }, END_GAME_TIMEOUT)
});

io.sockets.on(ROUND_END, () => {
  console.log("ROUND ENDED")

  setTimeout(() => {
    io.sockets.emit(ROUND_START);
  }, NEXT_GAME_TIMEOUT)
});

不从客户端发送与回合开始相关的任何信息的想法是因为回合必须在套接字之间进行同步。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

我通常在套接字连接到服务器时附加。我在https://socket.io/get-started/chat

上使用了聊天示例

完整的服务器配置

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

const NEXT_GAME_TIMEOUT = 5000;
const END_GAME_TIMEOUT = 10000;
const FULL_GAME_TIMEOUT = END_GAME_TIMEOUT + NEXT_GAME_TIMEOUT;
const ROUND_START = "ROUND_START";
const ROUND_END = "ROUND_END";

io.on('connection', function(socket) {
    console.log("user connected!!!");
    socket.on(ROUND_START, () => {
        console.log("ROUND STARTED")

        setTimeout(() => {
        io.sockets.emit(ROUND_END);
        }, END_GAME_TIMEOUT)
    });

    socket.on(ROUND_END, () => {
        console.log("ROUND ENDED")

        setTimeout(() => {
        io.sockets.emit(ROUND_START);
        }, NEXT_GAME_TIMEOUT)
    });
})