我正在使用NestJS处理Node.js应用程序。我需要与其他2个应用进行通信。
第一个通过WebSockets(Socket.io),另一个通过TCP套接字和网络模块。
是否可以使用两个具有特定适配器的网关,一个基于Socket.io,另一个基于Net模块,或者我是否必须拆分此应用程序?
您不需要拆分应用程序。
您可以将模块定义为:
@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)
})
}
}