Web socket constantly disconnecting in react app. Backend is Nestjs

Viewed 1634

I am trying to create a chat application and my web socket inside the client react application keeps disconnecting for some reason. And if I try to make the same connection from Vue application it works fine.

Below is my server side and client side code.

Server

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

@WebSocketGateway(4000)
export class ChatService implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {

    @WebSocketServer()
    private server: Server;

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

    @SubscribeMessage('events')
    handleEvent(client: Socket, data: string): string {
        console.log(data);
        client.emit('events', { name: 'Nest' }, data => console.log(data));
        return data;
    }

    @SubscribeMessage('msgToServer')
    public handleMessage(client: Socket, payload: string): void {
        this.server.emit('msgToClient', payload);
    }

    public afterInit(server: Server) {
        this.logger.log('Init');
    }

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

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

client side

import React from 'react';
import { io } from "socket.io-client";

const SERVER = "http://localhost:4000";
export class App extends React.Component {

    state = {
        channels: null,
        socket: null,
        channel: null
    }
    socket;

    componentDidMount() {
        this.configureSocket();
    }

    configureSocket = () => {
        var socket = io(SERVER);

        socket.on('connection', () => {
            console.log("here");
            socket.on('disconnect', (reason) => {
                console.log(reason);
            });
        });

        socket.on('msgToClient', (channel) => {
            console.log(channel);
        });
        socket.on('connect_error', (error) => {
            console.log(error);
        });
        socket.on('message', message => {
            console.log(message);
        });
        socket.on('disconnect', (reason) => {
            console.log(reason);
        });

        this.socket = socket;
    }

    handleSendMessage = () => {
        console.log("trying");

        this.socket.emit('send-message', { name: 'myname', text: 'mytext' });
    }

    render() {

        return (
            <div>
                help
                <button onClick={this.handleSendMessage}>send</button>
            </div>
        );
    }
}

Nothing is logged in the events as well from the frontend side. From the backend side The socket connects, and then disconnects. And thus starts reconnecting again and again. Without persisting the connection.

Any idea why is this so?

1 Answers

Socket.io v3 is not yet supported by Nest. You can find the issue here with a custom adapter to make them work together.

Related