You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Echo + Pusher:服务器不可用时如何停止尝试连接?

停止Laravel Echo(基于Pusher)连接失败后的重试尝试

Laravel Echo基于Pusher JS库实现,要停止连接失败后的重试,有两种直接可行的方式:


方式一:通过配置限制重试次数

Pusher JS原生支持retryAttempts配置项,直接在Echo初始化参数中添加该配置,就能指定最多重试次数(设为0则完全不重试)。

修改后的初始化代码:

const echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    wssHost: window.location.hostname,
    wssPort: 6001,
    encrypted: true,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ['wss'],
    // 添加这行,限制重试次数为0(连接失败后不再尝试)
    retryAttempts: 0
})

方式二:监听连接失败事件,手动终止重试

如果需要更灵活的控制(比如根据错误类型决定是否停止),可以监听Pusher连接的错误事件,触发后手动断开连接并阻止重试。

示例代码:

const echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    wssHost: window.location.hostname,
    wssPort: 6001,
    encrypted: true,
    forceTLS: false,
    disableStats: true,
    enabledTransports: ['wss'],
})

// 获取Pusher连接实例
const pusherConnection = echo.connector.pusher.connection;

// 监听连接错误事件
pusherConnection.bind('error', (error) => {
    // 可根据错误类型判断,比如仅在连接超时/服务器不可达时停止
    if (error.type === 'WebSocketError' || error.code === 1006) {
        // 断开连接
        pusherConnection.disconnect();
        // 阻止自动重试:移除所有重连定时器
        if (pusherConnection.reconnectTimer) {
            clearTimeout(pusherConnection.reconnectTimer);
            pusherConnection.reconnectTimer = null;
        }
    }
});

注意:第二种方式要确保在Echo初始化完成后再绑定事件,避免获取不到Pusher连接实例。

内容的提问来源于stack exchange,提问作者Sanya H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:05:18