F
F
Fannasankh2020-12-27 10:02:40
Socket.io
Fannasankh, 2020-12-27 10:02:40

Why is it not connecting to socket.io via Nest.js?

I create a socket.io server as in the documentation https://docs.nestjs.com/websockets/gateways
I even tried to run the official example published on github https://github.com/nestjs/nest/tree/master/sample/.. I can't connect, the

socket.on('connect') event doesn't fire, although the logs on the server show that the client connects and immediately disconnects

.

Client side code:

function connect():Promise<Socket> {
  

  const socket = io('http://localhost:4455', {
    transports: ['websocket'],

  });

  console.log('connect init');
  return new Promise((resolve) => {
    socket.on('connect', () => {
      resolve(socket);
      console.log('on connect');
    });
  });
}


On the server, the code according to the documentation

@WebSocketGateway({ transports: ['websocket'] })
export class SocketioGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  ioServer: Server;

  private logger: Logger = new Logger('SocketIO');

  afterInit(server: Server) {
    this.logger.log('SocketIO init');
  }

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

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`);
    return true;
  }

  emit(event: string) {
    this.ioServer.emit(`${event}`, true);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fannasankh, 2020-12-28
@Fannasankh

Nest is using socket.io version 2 which is not compatible with client version 3, issue resolved

A
Arkadiy_Stepanov, 2021-12-21
@Arkadiy_Stepanov

If not updated - build an Adapter for Websockets

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question