簡體   English   中英

為什么'new WebSocket()'不適用於nestjs?

[英]Why 'new WebSocket()' doesn't work for nestjs?

我正在發送const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world'); const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world'); 來自客戶端,我在服務器上收到日志“已連接”日志,但沒有收到“hello world”。 socket.send() 不適用於 NestJS。 當我查看 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();

查看 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);
  };
};

這應該可以解決問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM