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

如何在Pusher JS中监听通道关闭及连接超时事件?

你需要添加两类事件监听器,分别对应全局连接超时回调、单通道订阅超时回调,具体实现如下:


核心监听事件说明

  • 全局Pusher连接超时/异常:监听Pusher实例的error事件,可捕获所有连接层面的超时、权限错误等异常
  • 单个通道订阅超时:监听通道实例的pusher:subscription_timeout事件,专门捕获当前通道订阅超时的回调
  • 可选监听通道订阅失败事件pusher:subscription_error,可捕获订阅权限错误、通道不存在等其它订阅类异常

修改后完整代码

import Pusher from "pusher-js";
import { logoutUser } from "../redux/actions/authActions";
import store from "../redux/store/store";

const authSessionPusher = (sessionId) => {
  const pusher = new Pusher("xxxxxxxxxxxxxxxx", {
    cluster: "ap2",
    encrypted: true
  });

  // 新增:监听全局连接超时/异常
  pusher.connection.bind('error', (err) => {
    // 408为请求超时错误码,可按需调整匹配逻辑
    if (err.type === 'PusherError' && err.data?.code === 408) {
      // 此处填写连接超时时要执行的自定义逻辑
      console.log('Pusher连接超时', err)
    }
  })

  const channel = pusher.subscribe(sessionId);
  console.log(channel);

  // 新增:监听当前通道订阅超时
  channel.bind('pusher:subscription_timeout', () => {
    // 此处填写通道订阅超时时要执行的自定义逻辑
    console.log('通道订阅超时')
  })

  // 可选:监听通道订阅失败
  channel.bind('pusher:subscription_error', (err) => {
    console.log('通道订阅失败', err)
  })

  channel.bind("authSession", (data) => {
    if (data.message === "session logout") {
      store.dispatch(logoutUser());
    }
  });
};

export { authSessionPusher };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:39:03