代码之家  ›  专栏  ›  技术社区  ›  Roland Jegorov

socket.io未侦听全局事件

  •  0
  • Roland Jegorov  · 技术社区  · 6 年前

    我正在研究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)
    });
    

    不从客户端发送与round start相关的任何内容的想法是因为round必须跨套接字同步。

    我做错什么了?

    1 回复  |  直到 6 年前
        1
  •  0
  •   frithjof    6 年前

    我通常在套接字连接到服务器时附加。我在聊天室找到了这个例子 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)
        });
    })