nestjs websockets正在连接但无法接收消息

yvfmudvl  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(153)

我在使用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 {}
tmb3ates

tmb3ates1#

你可以检查你的socket客户端是否成功连接到nest网关

const socket = new WebSocket('ws://localhost:3000');
socket.onopen = function() {
  console.log('Connected');
  socket.send(
    JSON.stringify({
      event: 'events',
      data: 'test',
    }),
  );
  socket.onmessage = function(data) {
    console.log(data);
  };
};

https://github.com/nestjs/nest/tree/master/sample/16-gateways-ws上查看nestjs WebSocket网关的完整示例
无论如何:如果你使用SubscribeMessage装饰器,你必须遵循nestjs格式的消息。这是一个DTO喜欢

{event: string, data: any, error?: any, id?: string }

然后事件将与SubscribeMessage匹配

相关问题