reactjswebsocketsocket.ionestjsnestjs-gateways

Socket.io client is getting disconnected just after connection in NestJS


I'm trying to create chat with nestjs, and it is problem with its @SubscribeMessage(), implementation with connection is working, but when I try to listen the emits from frontend and console the data in nestjs, it not works

import { Server, Socket } from 'socket.io';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Repository } from 'typeorm';
import { Messenger } from './entities/messenger.entity';

@Injectable()
@WebSocketGateway(5000)
export class MessengerGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    @InjectRepository(Messenger)
    private messageRepository: Repository<Messenger>,
  ) {}

  @SubscribeMessage('loadPeople')
  handleEvent(client: Socket, data){
    console.log(data);
    // this is not working
  }

  async afterInit(server: Server) {
    console.log('Init');
  }

  @SubscribeMessage('is-online')
  async handleConnection(client: Socket) {
    console.log('connected');
    // I can see this message in console
  }

  @SubscribeMessage('is-offline')
  async handleDisconnect(client: Socket) {
    console.log('disconnected');
     // I can see this message in console
  }
}
enter image description here

from front end I'm sending this requests

import { io } from "socket.io-client";
const  ENDPOINT = "localhost:5000";
let socket

function App(){
  useEffect(()=>{
          socket = io(ENDPOINT)
          socket.emit('loadPeople', {token: localStorage.token})
  },[])

  return (
  //...
  )
}

It works when I'm using the nodejs(expressjs) with socket.io, But when I try to do this with nestjs, it's not working


Solution

  • 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.

    The easiest solution would be to use socket.io-client v2.3.0 in your package.json of frontend.

    Or, if you like to explore: 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 🍻 !!!