【问题标题】:How to Get websockets working with NestJS如何让 websockets 与 NestJS 一起工作
【发布时间】:2021-02-18 21:50:41
【问题描述】:

我在 nodejs 中成功运行 websockets - 作为使用 wshttps://www.npmjs.com/package/ws 的命令行 websockets 服务器

我无法让 nestjs websockets 网关正常工作。我努力了: https://docs.nestjs.com/websockets/gateways - 以及 github 上的工作示例; https://github.com/nestjs/nest/tree/master/sample/02-gateways 。它运行 - 但我无法连接到它。

如果我在 nodejs 中使用 ws 客户端进行连接,我会得到: Error: socket hang up

我也试过https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en 连接。我可以用它连接到其他 websocket 服务器。

我也试过这个https://techformist.com/websockets-app-nestjs/,它说

[Nest] 29036   - 06/11/2020, 6:42:02 pm   [NestFactory] Starting Nest application...
[Nest] 29036   - 06/11/2020, 6:42:02 pm   [InstanceLoader] AppModule dependencies initialized +11ms
[Nest] 29036   - 06/11/2020, 6:42:03 pm   [AppGateway] Initialized
[Nest] 29036   - 06/11/2020, 6:42:03 pm   [NestApplication] Nest application successfully started +3ms

看起来它正在工作 - 但我仍然无法连接。

我做错了什么?

更新: 下面是我的网关代码(来自https://techformist.com/websockets-app-nestjs/

import {
  SubscribeMessage,
  WebSocketGateway,
  OnGatewayInit,
} from "@nestjs/websockets";
import { Logger } from "@nestjs/common";

@WebSocketGateway(3026)
export class AppGateway implements OnGatewayInit {
  private logger: Logger = new Logger("AppGateway");

  afterInit (server: any) {
    // throw new Error('Method not implemented.'); - comment this
    this.logger.log("Initialized");
  }
  // export class AppGateway {
  @SubscribeMessage("message")
  handleMessage (client: any, payload: any): string {
    return "Hello world!";
  }
}

【问题讨论】:

  • 显示你的 Nest js ws 网关代码...
  • @ZainUrRehman 我已经更新了.. 我只是使用其中一个示例。然后我尝试连接到:ws://localhost:3026

标签: nestjs


【解决方案1】:

我找到了答案。我试图为此使用默认值,即 socket.io

我只需要适应 ws(Nestjs 也支持)并将其用作默认值。

在 main.ts 中

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/platform-ws' //Add this line

async function bootstrap () {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new WsAdapter(app)) // Add this line
  await app.listen(3000);
}
bootstrap();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 2017-06-25
    • 2020-12-13
    • 2012-02-02
    • 2011-02-22
    • 2013-03-24
    • 2016-07-22
    • 2011-08-17
    相关资源
    最近更新 更多