docs.nestjs.com icon indicating copy to clipboard operation
docs.nestjs.com copied to clipboard

Add tutorial for Nest Websocket Client

Open goodmanpersonguy opened this issue 6 years ago • 14 comments

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request (new chapter/page)
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

So the docs here

Gateways

describe really well, how to create a websocket server. Unfortunately I didn't find anything about a client setup.

Expected behavior

I would expect an additional chapter for socket clients

What is the motivation / use case for changing the behavior?

Currently I have a websocket server with a standard frontend client. I want to extend this project with a second Nest backend which should also connect as a socket client. It would be nice to have a tutorial on how to make this Nest application a socket client listening to events etc.

goodmanpersonguy avatar Nov 26 '19 15:11 goodmanpersonguy

This exactly what I'm looking for as well. I want to build a Nest Websocket Client that connects to a Cryptocurrency exchange's websocket server for market/pricing data, and then push received messages into Kafka. While I could easily do this without Nest; the data feed service is just part of an overall automated trading system that has many other components built using Nest.

Until an official solution is provided, my plan is to build a custom transport strategy loosely based on this documentation: https://docs.nestjs.com/microservices/custom-transport

Here's a few more resources that I think will be helping in hacking together a websockets client; they at least resemble the use case:

  • Kafka Microservice: https://github.com/nestjs/docs.nestjs.com/blob/docs/microservices-improvements/content/microservices/kafka.md
  • https://github.com/Racer159/nestjs-rmq

Any other resources that are a little more direct, would be much appreciated!

cnaccio avatar Jan 05 '20 07:01 cnaccio

Hey guys @goodmanpersonguy @cnaccio ! Any luck with figuring out how to properly make Nestjs WebSocket Client application/module? Definitely worth to update documentation on how to work with WS client in Nestjs.

Perf avatar Feb 18 '20 19:02 Perf

Also looking for this. We have multiple servers. All are web-socket servers. But some are also clients of the other servers.

MulderNick avatar Jun 23 '20 08:06 MulderNick

I'm also trying to solve this. Nest Websocket Client connecting to Nest Websocket Server. Any solutions so far?

StefanErler avatar Dec 19 '20 00:12 StefanErler

I'm looking for that too. Too bad it still doesn't have socket client support.

investeusa avatar Mar 31 '21 13:03 investeusa

I found this article series useful. Although it deals with NATS transport, the concept applies to other transports too.

zub0r avatar Mar 31 '21 13:03 zub0r

@goodmanpersonguy @cnaccio ! I found this example for angular, since nestjs is based on angular I implemented the same solution that they raised for angular and it worked (sorry for my bad english)

nest g resource Socket

in socketService implement the methods for the socket

import {Injectable} from '@ nestjs / common';
import * as io from 'socket.io-client';
import {Observable} from 'rxjs';
import {env} from 'node: process';

@Injectable ()
export class SocketService {
  private url = process.env.SOCKET_URL;
  private socket;

  connect () {
    this.socket = io (this.url);
  }

  emit (emitName: string, data?) {
    this.socket.emit (emitName, data);
  }

  on (onName: string) {
    let observable = new Observable ((observer) => {
      this.socket.on (onName, (data) => {
        observer.next (data);
      });

      return () => {
        this.socket.disconnect ();
      };
    });
    return observable;
  }
}

in socketGateway implement your use

import {
  WebSocketGateway,
  OnGatewayInit,
  OnGatewayDisconnect
} from '@ nestjs / websockets';
import {SocketService} from './socket.service';

@WebSocketGateway ()
export class SocketGateway implements OnGatewayInit, OnGatewayDisconnect {
  connection: any;
  data: any;
  message: any;
  constructor (private readonly socketService: SocketService) {}
  afterInit () {
    this.socketService.connect ();
    this.connection = this.socketService.on ('connect'). subscribe ((data) => {
      console.log (data);

      this.message = data;
    });
    let message = {
      service: '' asdsadsad ",
      ip: "",
      port: ""
    };
    this.socketService.emit ('notify', message);
  }
  handleDisconnect (client: any) {
    throw new Error ('Method not implemented.');
  }
}

lrlago avatar May 20 '21 14:05 lrlago

any working solutions?

rama41222 avatar Jul 10 '21 11:07 rama41222

@goodmanpersonguy I just released a module for use websocket-client with nestjs. I'd love you feedback guys :D

cc: @cnaccio @Perf @MulderNick @StefanErler @investeusa @zub0r @lrlango @lrlago

0xslipk avatar Sep 17 '21 21:09 0xslipk

@goodmanpersonguy I just released a module for use websocket-client with nestjs. I'd love you feedback guys :D

cc: @cnaccio @Perf @MulderNick @StefanErler @investeusa @zub0r @lrlango @lrlago

thanks, i used your module. However, I have a problem as follows, when the connection to the server side is closed, now I don't know how to reopen that connection. I'd love you feedback guys :D

viethrk avatar Nov 09 '21 09:11 viethrk

I followed this documentation and it worked perfectly. Hope it helps you guys in some way. They're sorry if I got my English wrong.

https://www.npmjs.com/package/nestjs-websocket

TiagoLima411 avatar Nov 17 '21 12:11 TiagoLima411

I followed this documentation and it worked perfectly. Hope it helps you guys in some way. They're sorry if I got my English wrong.

https://www.npmjs.com/package/nestjs-websocket

Happy to hear that, let me know if you have any problems

0xslipk avatar Nov 17 '21 13:11 0xslipk

@goodmanpersonguy I just released a module for use websocket-client with nestjs. I'd love you feedback guys :D

cc: @cnaccio @Perf @MulderNick @StefanErler @investeusa @zub0r @lrlango @lrlago

thanks, i used your module. However, I have a problem as follows, when the connection to the server side is closed, now I don't know how to reopen that connection. I'd love you feedback guys :D

Sorry to hear that, can you push a repository with the implementation? Or open an issue in the repository of nestjs-websocket with the steps need it to reproduce the problem.

Thanks

0xslipk avatar Nov 17 '21 13:11 0xslipk

I followed this documentation and it worked perfectly. Hope it helps you guys in some way. They're sorry if I got my English wrong. https://www.npmjs.com/package/nestjs-websocket

Happy to hear that, let me know if you have any problems

Below is my module

import { Module, HttpModule, Injectable } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { WebSocketModule } from 'nestjs-websocket';

@Injectable()
class ConfigService {
  public readonly url = 'wss://youendipoint.com./';
}

@Module({
  imports: [
    HttpModule,
    WebSocketModule.forRootAsync({
      providers: [ConfigService],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => {
        return {
          url: config.url,
        };
      },
    }),
  ],
  providers: [TasksService],
})
export class TasksModule {}

Below is my service

import { Injectable, Logger } from '@nestjs/common';
import {
  InjectWebSocketProvider,
  WebSocketClient,
  OnOpen,
  OnMessage,
} from 'nestjs-websocket';

@Injectable()
export class TasksService {
  private data: Record<any, any> = {};

  constructor(
    @InjectWebSocketProvider()
    private readonly ws: WebSocketClient,
  ) {}

  @OnOpen()
  open() {
    console.log('The connection is established.');
    this.ws.send(
      JSON.stringify({payload: "payload"}),
    );
  }

  @OnMessage()
  message(data: WebSocketClient.Data) {
    this.data = JSON.parse(data.toString());
    console.log(this.data);
  }
}

Very simple ;)

TiagoLima411 avatar Nov 17 '21 17:11 TiagoLima411