Here a stackblitz of the problem:
How the hell do you (delete / destroy / release) a WebSocket instance???
export class MyWebsocketService {
public url;
_constructor( URL:string ) {
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => { // blablabla }
this.ws.onmessage = () => { // blablabla }
this.ws.onclose = () => {
/////// I CANNOT for the life of me destroy that WebSocket instance from memory
/////// These are all the solutions online:
this.ws.onopen = null;
this.ws.onmessage = null;
this.ws.onclose = null;
this.ws.onerror = null;
this.ws.close();
this.ws = null;
delete this.ws;
setTimeout( _ => {
console.log('Reconnecting...');
this.connect();
}, 3000);
}
}
}
...
public websocket;
createWebsocketsServices() {
this.websocket = new MyWebsocketService('wss://whatever');
// HERE I'm changing the URL
this.websocket = new MyWebsocketService('wss://my-new-url');
////////// BUT THE FIRST WEBSET IS STILL IN MEMORY!!!!!!!
}
ngOnInit(): void {
this.createWebsocketsServices();
}
None of the solutions I found online actually resolve this issue
Understanding object creation and garbage collection of a NodeJS WebSocket server
WebSocket: How to automatically reconnect after it dies
///////////// EDITED ////////////////////
"What makes you assume that the websocket is kept in memory?" A detail I forgot to mention is: in my real life application say I try to connect to 4 dummy URL and after I connect to the valid one... the ws server register 4 new connections not 1. They are still alive
My goals:
- Try to connect to websocket
- if can't connect try to reconnect every 3 seconds
- Change the websocket url on runtime = (Destroy current ws instance + create new ws instance with new URL)
That's a hack that works for now
https://stackblitz.com/edit/angular-ivy-vjezvq?file=src/app/app.component.ts
It doesn't resolve the issue the websocket is still not released from memory but I can at least change URL