【问题标题】:Socket.io room not being emitted toSocket.io 房间没有被发送到
【发布时间】:2020-01-08 03:27:46
【问题描述】:

我正在使用带有 React-native (expo) 前端的 NestJS 后端,并尝试通过 socket.io 库让这两者连接。

我能够从我的服务器向我的移动应用程序发送事件,但由于某种原因无法获得与特定房间关联的事件来触发。

我的移动应用代码:

  static socket = socketIOClient(HttpService.socketUrl + '/room', {
    transports: ['websocket'],
    reconnectionDelay: 1000,
    reconnection: true
  });

  //Called on button click
  static joinRoom(roomId) {
    console.log('subscribing to room', roomId); //This successfully logs to the console
    RoomListener.socket.emit('room-subscription', roomId);
    RoomListener.socket.on('room-event', function(data) {
       console.log(data); //This never happens!
    }
  }

和我的后端代码:

@WebSocketGateway(80, { namespace: 'room' })
export class RoomGateway implements OnGatewayConnection {
  @WebSocketServer() server: Server;

  handleConnection(client: any, ...args: any[]) {
    //These successfully log to the console
    console.log('connection');
    console.log(client.id);
  }

  @SubscribeMessage('room-subscription')
  async joinRoom(
    @MessageBody() data: string,
    @ConnectedSocket() socket: Socket,
  ): Promise<string> {
    console.log('adding to room ', data); //This successfully logs to the console
    socket.join(data);
    return data;
  }

  @SubscribeMessage('roomTest')
  roomTest(
    @MessageBody() data: string,
    @ConnectedSocket() socket: Socket,
  ): string {
    console.log('emitting to room', roomId); //This successfully logs to the console with the proper data
    this.server.in(roomId).emit('room-event', 'hello');

    return data;
  }
}

我也试过this.server.of('/room').in(roomId).emit('room-event', 'hello); 以及this.server.to(...).emit(...) 以及与this.server.sockets 相同的3 个组合。我无法找到关于它们之间区别的明确文档,并且对为什么我无法向我的移动应用发出信号感到困惑。

提前致谢!

【问题讨论】:

    标签: react-native socket.io expo nestjs


    【解决方案1】:

    试试:

    socket.to(roomId).broadcast.emit('room-event', created);
    

    【讨论】:

    • socket.to(roomId).broadcast.emit('room-event', 'hello');你试过这样吗?
    • 是的,我试过了,我仍然没有在前端得到任何日志,可能是由于命名空间的原因吗?
    • 我开始认为问题可能出在我的前端。看起来我可以发出一个事件,但即使做 RoomListener.on('connect', () => { console.log('hello") } ) 也不起作用
    • 检查你的socketUrl
    • 检查不同端口上的 WebSocket
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 2021-08-20
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-12
    • 2017-09-27
    相关资源
    最近更新 更多