我有一个用nest.js编写的应用程序。我也有网关,应该向用户发送一些数据。由于某种原因,我必须使用WsAdapter,而不是socket.io。我尝试使用socket.io做到这一点,并且工作正常,但是当我迁移到WsAdapter时,server.emit
返回false,并且数据没有发送到套接字。但是client.send
可以正常工作,这使它变得怪异。
main.ts:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/platform-ws';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app));
await app.listen(3000);
}
bootstrap();
currency.gateway.ts:
import {
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import {forwardRef, Inject, Logger} from '@nestjs/common';
import {Server} from 'ws';
import {CurrencyService} from './currency.service';
import {FiatService} from './fiat/fiat.service';
@WebSocketGateway(3001, { transports: ['websocket'] })
export class NativeCurrencyGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server: Server;
constructor(
@Inject(forwardRef(() => CurrencyService))
private readonly currencyService: CurrencyService,
@Inject(forwardRef(() => FiatService))
private readonly fiatService: FiatService,
) {}
sendCurrentCurrencies(currencies) {
const data = {
event: 'current_currencies',
data: currencies,
};
console.log(this.server.emit(JSON.stringify(data)));
}
sendCurrentFiats(fiats) {
const data = {
event: 'current_fiats',
data: fiats,
};
console.log(this.server.emit(JSON.stringify(data)));
}
afterInit(server: Server) {}
handleDisconnect(client: any) {}
handleConnection(client: any) {
this.currencyService.get().then(res => {
const data = JSON.stringify({
event: 'current_currencies',
data: res,
});
client.send(data);
});
this.fiatService.get().then(res => {
const data = JSON.stringify({
event: 'current_fiats',
data: res,
});
client.send(data);
});
}
}
P.S。是的,关于这个问题,我也看到了相同的question,但我想那里的答案没有任何意义。我的意思是,如果我们具有网关接口,那么该接口的任何实现都应该可以正常工作(在我的情况下,emit
方法应该可以在WsAdapter上工作)