Pergunta

I've created a rest generic service which additionally consume a websocket per resource my websocket code looks like so:

initialize(hubSubRoute: string): void{
    const accessToken = this.authManager.getRawAccessToken();

    let hubUrl = environment.baseUrl + hubSubRoute;
    if (accessToken) {
        hubUrl += '?' + this.hubAuthorizationQueryParameter +'=' + accessToken;
    }

    this._hubConnection = new HubConnectionBuilder()
                                .withUrl(hubUrl)
                                .build();
}

startConnection(): void {

    this._hubConnection.start()
        .then(() => {
            console.log('Hub connection started');
            this.connectionEstablished.emit(true);
        })
        .catch(err => {
            console.log('Error while establishing connection');
        });
}

I know web-sockets are long lived connection. I'm wondering the best practices for maintaining their longevity. For example I have a messages services. Which will open a websocket and post message as they come, in, However,

If the user navigates away from that conversation, should I leave the web-socket open?

Or Should I close it and when the user returns back to that conversation, just obtain the missing messages and reinitialize the web-socket?

Foi útil?

Solução

Creating a new connection is expensive in terms of resources. The goal of WebSocket is specifically to avoid creating connections on regular intervals, such as in the case of long polling.

However, maintaining an open connection is also expensive: if you have too many of them, you may not be able to open new ones (without additional network hardware, etc.)

Therefore:

  • If you're pretty sure the use won't be interested by the events for a long time, close the connection.

  • If you're running out of connections, close the ones which are inactive.

  • In other cases, just keep it open, which would also make your code simpler.

Licenciado em: CC-BY-SA com atribuição
scroll top