我在使用websockets设置nestjs时遇到问题。通过Chrome开发工具,我可以建立连接:
let socket = new WebSocket('ws://localhost:3000');
我可以在handleConnection
方法中设置一个断点,连接看起来很健康:
WebSocket {url: 'ws://localhost:3000/', readyState: 1, bufferedAmount: 0, onopen: null, onerror: null, …}
但是当我发送一条信息socket.send('hello testing');
。则不接收该消息。handleMessage
内部设置的断点不会被命中。
我不知道我做错了什么。
的界线在
app.useWebSocketAdapter(new WsAdapter(app));
正确和必要的?我不知道为什么我在一些在线示例中看不到这条线,但是没有它,我不能建立没有它的连接。app.gateway.ts
:
import { Logger } from '@nestjs/common';
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
OnGatewayConnection,
OnGatewayDisconnect,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
@WebSocketGateway()
export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
private wss: Server;
private logger: Logger = new Logger('AppGateway');
afterInit(server: Server) {
this.logger.log('Initialized!');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client connected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client disconnected: ${client.id}`);
}
@SubscribeMessage('*')
handleMessage(client: Socket, text: string): void {
this.wss.emit('msgToClient', text); // not hitting this line
}
}
main.ts
:
import { join } from 'path';
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { WsAdapter } from '@nestjs/platform-ws' //Add this line
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.enableCors();
app.useWebSocketAdapter(new WsAdapter(app)); // Add this line
await app.listen(3000);
}
bootstrap();
app.module.ts
:
import { Module } from '@nestjs/common';
import { AppGateway } from './app.gateway';
@Module({
imports: [],
controllers: [],
providers: [AppGateway],
})
export class AppModule {}
1条答案
按热度按时间tmb3ates1#
你可以检查你的socket客户端是否成功连接到nest网关
在https://github.com/nestjs/nest/tree/master/sample/16-gateways-ws上查看nestjs WebSocket网关的完整示例
无论如何:如果你使用SubscribeMessage装饰器,你必须遵循nestjs格式的消息。这是一个DTO喜欢
然后事件将与SubscribeMessage匹配