使用NestJS的多个套接字适配器

问题描述 投票:0回答:1

我正在使用NestJS处理Node.js应用程序。我需要与其他2个应用进行通信。

第一个通过WebSockets(Socket.io),另一个通过TCP套接字和网络模块。

是否可以使用两个具有特定适配器的网关,一个基于Socket.io,另一个基于Net模块,或者我是否必须拆分此应用程序?

node.js sockets tcp websocket nestjs
1个回答
0
投票

您不需要拆分应用程序。

您可以将模块定义为:

@Module({
  providers: [
    MyGateway,
    MyService,
  ],
})
export class MyModule {}

gateway负责网络套接字通道

import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets'
import { Socket } from 'socket.io'
...
@WebSocketGateway()
export class MyGateway {
  constructor(private readonly myService: MyService) {}

  @SubscribeMessage('MY_MESSAGE')
  public async sendMessage(socket: Socket, data: IData): Promise<IData> {
    socket.emit(...)
  }
}

并且service负责TCP频道

import { Client, ClientProxy, Transport } from '@nestjs/microservices'
...
@Injectable()
export class MyService {
  @Client({
    options: { host: 'MY_HOST', port: MY_PORT },
    transport: Transport.TCP,
  })
  private client: ClientProxy

  public async myFunction(): Promise<IData> {
    return this.client
      .send<IData>({ cmd: 'MY_MESSAGE' })
      .toPromise()
      .catch(error => {
        throw new HttpException(error, error.status)
      })
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.