简体   繁体   中英

Reconnect to Laravel Echo server after session disconnection

I am attempting to write an web application with a persistent echo connection to a laravel-echo-server instance, which needs to detect disconnections and attempt to reconnect gracefully. The scenario I am attempting to overcome now is a user's machine has gone to sleep / reawoke and their session key has been invalidated (echo server requires an active session in our app). Detecting this situation from an HTTP perspective is solved - I setup a regular keepAlive, and if that keepAlive detects a 400-level error, it reconnects and updates the session auth_token.

When my Laravel session dies, I cannot tell that has happened from an echo perspective. The best I've found is I can attach to the 'disconnect' event, but that only gets triggered if the server-side laravel-echo-server process dies, rather than the session is invalid:

        this.echoConnection.connector.socket.on('connect', function() {
            logger.log('info', `Echo server running`);
        })
        this.echoConnection.connector.socket.on('disconnect', function() {
            logger.log('warn', `Echo server disconnected`);
        });

On the laravel-echo-server side, I can tell that the connection is dead - it will show this error:

⚠ [7:03:30 PM] - 5TwHN2qUys5VEFP5AAAG could not be authenticated to private.1

I cannot figure out how to catch this failure event programmatically from the client. Is there a way to capture it? Again, I can tell the session is dead eventually because I poll the server regularly via a http keepAlive function, but I would definitely also like to tell directly from the echo connection if possible, as it polls at a much higher natural rate.

As a second (more important) question, if I detect that my session has died, what should I do to recycle the echo connection (after I have logged in again via HTTP and gotten a new auth_token)? Is there anything specific I should call / etc? I've had some success calling disconnect() then setting up the connection again from scratch, but I do see errors such as:

websocket.js:201 WebSocket is already in CLOSING or CLOSED state.

Here is my current (naive) reconnection code, which is my initial connection code with an attempt to disconnect first stapled onto it:

    async attemptEchoReconnect() {

        if (this.echoConnection !== null) {
            this.echoConnection.disconnect();
            this.echoConnection = null;
        }

        const thisConnectionParams = this.props.connections[this.connectionName];
        const curThis = this;

        this.echoConnection = new Echo({
            broadcaster: 'socket.io',
            host: thisConnectionParams.echoHost,
            authEndpoint: 'api/broadcasting/auth',
            auth: {
                headers: {
                    Authorization: `Bearer ` + thisConnectionParams.authToken
                }
            }
        });

        this.echoConnection.connector.socket.on('connect', function() {
            logger.log('info', `Echo server running`);
        })
        this.echoConnection.connector.socket.on('disconnect', function() {
            logger.log('warn', `Echo server disconnected`);
        });

        this.echoConnection.join('everywhere')
            .here(users => {
                logger.log('info', `Rejoined presence channel`);
            });

        this.echoConnection.private(`private.${this.props.id}`)
            .listen(...);

        setTimeout(() => { this.keepAlive() }, 120 * 1000);
    }

Any help would be so great - these APIs are not well documented to the end that I really want, and I am hoping I can get some stability with this connection rather than having to do something ugly like force restart.

For anyone who needs help with this problem, my above echo reconnection code seems to be pretty stable, along with a keepAlive function to determine the state of the HTTP connection. I am still a bit uncertain of the origin of the console errors I am seeing, but I suspect they have to do with connection loss during a sleep cycle, which is not something I am particularly worried about.

I'd still be interested in hearing other thoughts if anyone has any. I am somewhat inclined to believe long-term stability of an echo connection is possible, though it does appear you have to proactively monitor it with what tools you have available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM