我可以建议你 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);
}