Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get websockets working with NestJS

Tags:

nestjs

I successfully run websockets in nodejs - as a command line websockets server using wshttps://www.npmjs.com/package/ws

I cannot get nestjs websockets gateway working. I have tried: https://docs.nestjs.com/websockets/gateways - and the working example at github here; https://github.com/nestjs/nest/tree/master/sample/02-gateways . It runs - but I cannot connect to it.

If I use ws client in nodejs to connect, I get : Error: socket hang up

I have also tried https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo?hl=en to connect . I can connect with this to other websocket servers.

I also tried this one https://techformist.com/websockets-app-nestjs/ and it says

[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

Which looks like it is working - but I still cannot connect.

What am I doing wrong?

Update: My gateway code below ( from is 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!";
  }
}
like image 680
Martin Thompson Avatar asked Mar 01 '23 22:03

Martin Thompson


1 Answers

I found the answer to this. I was trying to use the default for this which is socket.io

I just needed to adapt to ws ( which is also supported by Nestjs ) and use that as the default.

in 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();
like image 188
Martin Thompson Avatar answered May 01 '23 09:05

Martin Thompson