node.jstypescriptwebsocketnestjsws

Messages not reaching handler while using WebSocket and nestjs


I am trying to implement WebSocket into nestjs app and I have problems with messages not reaching my handler in nestjs.

I am able to connect both ends and send message from nestjs to client but not the other way.

this is my nestjs code: (please note that i am not using socket.io i am implementing ws as WebSocket

import {
    OnGatewayInit,
    WebSocketGateway,
    WebSocketServer,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';

@WebSocketGateway(5015)
export class ExportFeedsGateway implements OnGatewayInit {
    @WebSocketServer() wss: any;

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

    afterInit(server: any): any {
        this.logger.log('Export Feeds Initialized');
    }

    handleConnection(client) {
        client.send('message from server'); // this message is properly send and read on the client side
    }

    handleMessage(message) {
        console.log('message', message); // this is never logged in nest
    }
}

and some client code:

const WebSocket = require( 'ws');

    ...

        this.ws = new WebSocket('ws://localhost:5015');
        this.ws.on('open', () => {
            this.ws.send('message from client') // this message never reaches server
        });

    ...

Question is what is the problem with nestjs messages handler that it doesnt pick up messages?


Solution

  • You're missing the @SubscribeMessage('message') that you'll need for Nest to register the handler to the websocket server. handleConnection is a bit of a special case method as defined inthe lifecycle methods. Also, when sending the message from the ws library, use the form: ws.send('{"event": "message", "data": whateverDataObjectYouWant }', callback). This way, Nest can parse the event and properly route it