websocket state 3 while sending message after reconnect

Viewed 13

I encountered odd problem when working with websocket. I am not sure exactly what is the reason for whats happening.

I have this simple websocket client that is implemented into nestjs service

import { Injectable } from '@nestjs/common';
import * as WebSocket from 'ws';
import { timer } from 'rxjs';

@Injectable()
export class ImportFeedsGateway {
    private ws: WebSocket;

    constructor() {
        this.connect();
    }

    private connect() {
        this.ws = new WebSocket(process.env.URL);
        this.ws.on('open', () => {
            this.ws.send(Math.random()); // this message is always send properly and this.ws state is 1 when logged after reconnect
        });

        this.ws.on('message', (message) => {
            ...
        });

        this.ws.on('error', (message) => {
            this.ws.close();
        });

        this.ws.on('close', (message) => {
            timer(1000).subscribe(() => {
                this.connect();
            });
        });
    }

    sendMessage(message) {
        this.ws.send(message); // this message is never send after reconnect and this.ws state is 3 when logged
    }
}

So the problem is that after reconnect Math.random() message is always properly sent while attempt to use sendMessage method results in fail because this.ws state always is 3.

It seems like this.ws points to different places depending on if its accessed from outside of class (via sendMessage method) or from inside (via on('open', callback). Inside callback its always current this.ws while sendMessage accesses old this.ws in closed state. Its like this.ws reference is not wired properly.

Does anyone know why is that and how to fix it?

---- EDIT

after transforming sendMessage method to its arrow version, its working correctly, but its more of puzzle now why

sendMessage = (message) => {
    this.ws.send(message); // with arrow version this.ws is always in state 1 and its working correctly
}
0 Answers
Related