简体   繁体   English

为什么'new WebSocket()'不适用于nestjs?

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

I am sending with const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world');我正在发送const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world'); const socket = new WebSocket('ws://localhost:3000'); socket.send('hello world'); from client and i receive log 'connected' log on the server but not 'hello world'.来自客户端,我在服务器上收到日志“已连接”日志,但没有收到“hello world”。 socket.send() not working for NestJS. socket.send() 不适用于 NestJS。 When I look at chrome network.当我查看 chrome 网络时。 It sends the data but not receiving in server.它发送数据但未在服务器中接收。 here is the code: chat.gateway.ts这是代码: 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 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();

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

On the client side:在客户端:

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

This should do the trick这应该可以解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM