Emit websocket event from a NestJS controller or service

Mik*_*lis 8 websocket socket.io nestjs

I am trying to listen to model change events in TypeORM through a subscriber, and broadcast an event each time a new one is inserted. While external clients receive the event, the gateway's @SubscribeMessage() method is not receiving it, which suggests that the sender is not getting the event. However, according to socket.io, the of('namespace').emit('event') should be received to any client, including the sender.

网关被注入订阅者服务,没有任何问题,并且当我尝试使用它时,网关的服务器似乎已准备好,但没有发出任何事件。

在 NestJS 6.3.1 上运行,我也尝试从控制器发出事件,但没有结果。

@WebSocketGateway({ namespace: '/posts' })
export class PostGateway {

  @WebSocketServer()
  server: Namespace;

  @SubscribeMessage('create')
  handleMessage(client: Socket, payload: Post): void {
    console.log('handling', payload);
  }

}
Run Code Online (Sandbox Code Playgroud)
@Injectable()
export class PostSubscriber implements EntitySubscriberInterface<Post> {

  private socket: Namespace;

  constructor(
    @InjectConnection() readonly connection: Connection,
    private readonly gateway: PostGateway,
  ) {
    connection.subscribers.push(this);
    this.socket = gateway.server;
  }

  listenTo() {
    return Measurement;
  }

  afterInsert(event: InsertEvent<Post>): void {
    this.gateway.server.emit('create', event.entity);
  }

}

Run Code Online (Sandbox Code Playgroud)

小智 0

我不太确定您的代码中的问题是什么。但我可以提供一些东西来检查。以下是一些建议:

  1. 确保 PostGateway 已连接且其服务器已正确初始化。

  2. 检查命名空间连接

    if (!this.socket) { console.error('Socket is not initialized!'); }

  3. 在主模块中检查网关初始化

  4. 调试发出事件

  5. 检查客户端是否正确连接到指定的命名空间 (/posts) 并订阅“create”事件。

    socket.on('create', (data) => { console.log('收到创建事件:', data); });