【问题标题】:Nestjs Gateways websocket as clientNestjs Gateways websocket 作为客户端
【发布时间】:2021-02-05 20:31:54
【问题描述】:

我如何在 nestjs 中创建到 Web 套接字服务器的客户端连接。

例如:有一个 web socket 或 socket.io 服务器每秒向它的所有客户端发送一条消息。

如何在 nestjs 中正确连接到此服务器并收听来自它的消息事件。我是否必须为我的 WebSocketGateway 创建一个特殊的适配器才能成为客户端? 是否有可能让 Websotsketgateva 成为客户?如果没有,正确的做法是什么?

【问题讨论】:

    标签: websocket socket.io nestjs


    【解决方案1】:

    我可以建议你 2 种方法

    1:创建实现 WebSocketAdapter 的适配器。然后你可以使用@SocketGateway 和@SubscribeMessage。你可以阅读更多:Connect NestJS to a websocket server

    2:创建一个提供者实现 OnApplicationBootstrap。在此提供程序中,您安装您的套接字客户端,并从它触发事件到 EventEmitor。

    
    @Injectable()
    export class IoClientGatewayBootstrap implements OnApplicationBootstrap {
      @Inject(IoClient)
      private ioClient: IoClient;
      @Inject(GLOBAL_PROVIDER.LOCAL_EVENT_EMITOR)
      private localEventEmitor: LocalEventEmitorInterface;
    
      onApplicationBootstrap() {
        console.log('run');
    
        this.connect();
      }
    
      connect = () => {
        const connection = io(AppConfig.SOCKET_SERVER_URL);
    
        connection.on('connect', () => {
          console.log('ok connect');
        });
    
        connection.on('disconnect', (reason) => {
          console.log('disconnect', reason);
        });
    
        // swap socket event to local event
        connection.onAny((eventName: string, ...args) => {
          console.log(eventName);
          this.localEventEmitor.emit(eventName, args);
        });
    
        this.ioClient.setIoClient(connection);
      };
    }
    
    

    其中 localEventEmitor 是一个服务实现 EventEmitter2 (https://docs.nestjs.com/techniques/events)

    import { Injectable } from '@nestjs/common';
    import { EventEmitter2 } from '@nestjs/event-emitter';
    import { LocalEventEmitorInterface } from './local-event-emitor.interface';
    
    @Injectable()
    export class LocalEventEmitor implements LocalEventEmitorInterface {
      constructor(private eventEmitter: EventEmitter2) {}
    
      emit = (
        event: string,
        data: any,
      ) => {
        this.eventEmitter.emit(event, data);
      };
    
      
    }
    

    现在您可以在任何您想要的模块中将套接字事件作为本地事件进行侦听

     @OnEvent('test-my-event')
      handleEvent(event: unknown) {
        console.log(event);
      }
    

    【讨论】:

      猜你喜欢
      • 2021-07-06
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2015-01-14
      相关资源
      最近更新 更多