nest js websocket connection is not working with angular 11

Viewed 4315

Created a nest js websocket and trying to connect to that from angular app version 11. Not able to connect to socket from angular 11. I am using latest version of socket.io-client.

In websocket server log says connect and disconnects.

nest js websocket file:

import { Logger } from '@nestjs/common';
import { OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit, SubscribeMessage, WebSocketGateway, WsResponse } from '@nestjs/websockets';
import { Socket,Server } from 'socket.io';

import { EventPattern } from '@nestjs/microservices';

@WebSocketGateway(3001)

export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect{
    private Logger = new Logger('AppGateway');

    afterInit(server: Server) {
        this.Logger.log("App Gateway Initialized");
    }

    handleConnection(client: Socket, ...args: any[]){
        this.Logger.log(`New client connected...: ${client.id}`);
        client.emit('connected', 'Successfully connected to the server.');
    }

    handleDisconnect(client: Socket) {
        this.Logger.log(`Client disconnected: ${client.id}`);
    }

    @SubscribeMessage('msgToServer')
    handleMessage(client:Socket, text:string):WsResponse<string> {
        this.Logger.log(`got new event`);
        return {event: 'msgToClient', 'data': text};
    }
}

angular websocket service file:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client';

@Injectable({
  providedIn: 'root'
})
export class WebSocketService {

  socket: any;

  constructor() {
    this.socket = io('http://localhost:3001');
    debugger;

    this.socket.on('connected', function() {
        console.log("connected !");
    });

  }

  listen(eventName: string) {
    return new Observable((subscriber) => {
      this.socket.on(eventName, (data) => {
        subscriber.next(data);
      })
    });
  }

  emit(eventName: string, data:any) {
    this.socket.emit(eventName, data);
  }
}

angular app.component.ts file:

import { Component, OnInit } from '@angular/core';
import { WebSocketService } from './web-socket.service';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit{
  title = 'dashboard';


  constructor(
    private webSocketService: WebSocketService
  ) {}

  ngOnInit() {
    /*this.webSocketService.listen('msgToClient').subscribe((data) => {
      console.log(data);
    })*/

    this.webSocketService.listen('connected').subscribe((data) => {
      console.log(data);
    })
  }
}
1 Answers

I am using latest version of socket.io-client.

I believe you're using socketIO client v4. (If you're working with v3, the following would still be true)

Based on NestJS Websocket documentation, the NestJS socketIO server is still in v2.

@nestjs/platform-socket.io currently depends on socket.io v2.3 and socket.io v3.0 client and server are not backward compatible. However, you can still implement a custom adapter to use socket.io v3.0. Please refer to this issue for further information.

If you check the version compatibility, you will see that socketIO server v2 is not compatible with socketIO client v4.

However, socketIO server v3 is compatible with socketIO client v4. So I believe you can take a look into this issue (as mentioned in NestJS docs) and try to convert your NestJS socketIO server to support socketIO client v3. Hopefully, that would also support socketIO client v4 as well. (I didn't test this though!)

Hope this helps you. Cheers !!!

Related