首页 > 解决方案 > Socket.IO 发射到特定房间不起作用,它正在发送到所有套接字

问题描述

我正在使用 socket.to('XYZ') 发送到房间,但由于某种原因,它正在发送到不在房间内的套接字。有谁知道为什么会发生这种情况?这是一个屏幕截图,如您所见,我在房间 PPPC 中寻找插座,但它返回的插座不在那个房间里。任何帮助将不胜感激,谢谢!

在房间里寻找插座 PPPC

使用随机房间进行测试也会返回所有套接字

编辑 - 添加了更多代码:

/game在我的服务器文件中创建命名空间:命名空间

然后我在我的 Game 类中导入该命名空间

稍后在我调用的一种方法中this.socket.to('PPCC').emit(...),此消息将发送到所有套接字,而不仅仅是房间中的套接字。我确认接收消息的套接字不在它发送到的房间中。

当我调试时,我发现this.socket.to('PPCC').sockets返回的套接字不在房间“PPCC”中。

索引.ts:

export const g = io.of("/game");
g.on("connection", (client) => {
  const { id: room, uid, nick } = client.handshake.query;
  const game = Game.getGame(room);
  console.log(`Connection in lobby ${room} (${nick})`);
  if (!game) {
    console.log("404 game does not exist");
    return client.disconnect(true);
  }

  const player = game.getPlayer(uid);
  if (!player) {
    console.log("Player does not exist");
    return client.disconnect(true);
  }

  client.join(room);
  player.active();
  game.checkActive();
  g.to(room).emit("lobby", game.state.players);
  client.emit("game", game.serialize());

  if (player.state.drawing) {
    client.emit("drawing", game.state.currentWord);
  }
  
  game.emitMessage();
});

游戏.ts

import { g } from "..";

class Game {
   constructor() {
    this.socket = g; // imported from server file
    this.id = 'ABCD'
    }
   emitMessage() {
     this.socket.to(this.id).emit(...) // sent to all sockets
     // note- I ran this.socket.to(this.id).sockets and found that it contained sockets not in the room
   }
}

标签: socket.io

解决方案


推荐阅读