为什么在nestjs中 'new WebSocket()' 无法工作?

3

我正在使用客户端发送const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world');,服务器端的日志记录了'connected',但没有记录'hello world'。NestJS中的socket.send()无法工作。当我查看Chrome网络时,它发送了数据,但服务器端未能接收到。

以下是代码:chat.gateway.ts

@WebSocketGateway()
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
  handleConnection(client: any, ...args: any[]): any {
    console.log('connected');
  }

  handleDisconnect(client: any): any {
    console.log(client);
    console.log('disconnected');
  }

  @SubscribeMessage('message')
  handleEvent(client: any, data: any): WsResponse<any> {
    const event = 'events';
    return { event, data };
  }

  afterInit(server: any): any {
    console.log(server.path);
  }
}

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.enableCors({
    origin: 'http://localhost:4200',
    credentials: true,
  });
  app.useWebSocketAdapter(new WsAdapter(app));
  await app.listen(3000);
}

bootstrap();
1个回答

4

请查看Github示例:https://github.com/nestjs/nest/tree/master/sample/16-gateways-ws

在客户端方面:

const socket = new WebSocket('ws://localhost:80');
socket.onopen = () => {
  console.log('Connected');
  socket.send(
    JSON.stringify({
      event: 'message',
      data: 'my very important message',
    }),
  );
  socket.onmessage = (data) => {
    console.log(data);
  };
};

这应该能解决问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接