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

React-Native集成Server Sent Event出现循环连接异常求助

React-Native SSE集成异常:无间隔重复触发waiting事件并循环请求

我尝试在React-Native中使用react-native-sse包集成Server-Sent Events,以下是放在应用主栈中的代码:

useEffect(() => {
  const url = new URL("https://your-sse-server.com/.well-known/mercure");

  const es = new EventSource(url, {
    headers: {
      UserId: "123",
      Authorization: "123",
      "X-Api-Key": "0242ac120002",
    },
    method: "PATCH",
  });

  const listener = event => {
    if (event.type === "open") {
      console.log("Open SSE connection.");
    } else if (event.type === "waiting") {
      console.log(`Received waiting`);
    } else if (event.type === "success") {
      console.log(`Received success`);
    } else if (event.type === "error") {
      console.error("Connection error:", event.message);
    } else if (event.type === "exception") {
      console.error("Error:", event.message, event.error);
    }
  };

  es.addEventListener("open", listener);
  es.addEventListener("waiting", listener);
  es.addEventListener("success", listener);

  return () => {
    es.removeAllEventListeners();
    es.close();
  };
}, []);

启动应用后,控制台日志如下:

LOG  Open SSE connection.
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Open SSE connection.
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Open SSE connection.
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Received waiting
LOG  Open SSE connection.

问题:Received waiting无间隔重复打印,同时应用会持续循环向目标接口发起请求。但该接口在Postman中运行正常,每2秒返回一次waiting内容。


解决思路及方案

  1. 修正请求方法
    SSE标准要求使用GET方法发起请求,你当前配置的PATCH不符合规范,服务器会直接断开连接,触发客户端反复重连,导致循环打开连接和触发waiting事件。修改配置:
const es = new EventSource(url, {
  headers: {
    UserId: "123",
    Authorization: "123",
    "X-Api-Key": "0242ac120002",
  },
  method: "GET", // 改为GET,或者直接删除该字段(默认是GET)
});
  1. 验证服务器响应格式
    确保服务器返回的响应严格遵循SSE规范:
  • 响应头Content-Type必须是text/event-stream
  • 响应体内容需用data: 前缀包裹,结尾要加\n\n换行,比如:
    data: waiting
    
    
  1. 调整重连间隔
    如果上述调整后仍有问题,可以显式设置客户端重连间隔,和服务器返回频率保持一致:
const es = new EventSource(url, {
  // 其他配置...
  reconnectInterval: 2000, // 设置为2秒
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 03:50:01