当前位置: 首页 > article >正文

hyperlane使用SSE实现服务端主动推送

GITHUB 地址

hyperlane 框架支持 SSE,服务端主动推送,下面是每隔 1s 完成一次推送,并在 10 次后关闭连接

SSE 规范: 服务器使用 “Content-Type: text/event-stream” 表示响应是一个 SSE 事件流。
接着使用 “data” 字段来发送事件数据,每个事件以 “data:” 开头,后面跟着事件的内容和一个空行。
客户端收到这样的响应后,就可以解析其中的事件数据并进行相应的处理。

服务端代码

use crate::{tokio::time::sleep, *};
use std::time::Duration;

pub async fn root(controller_data: ControllerData) {
    let _ = controller_data
        .set_response_header(CONTENT_TYPE, TEXT_EVENT_STREAM)
        .await
        .send_response(200, "")
        .await;
    for i in 0..10 {
        let _ = controller_data
            .send_response_body(format!("data:{}{}", i, HTTP_DOUBLE_BR))
            .await;
        sleep(Duration::from_secs(1)).await;
    }
    let _ = controller_data.close().await;
}

客户端代码

客户端代码

断线重连
const eventSource = new EventSource('http://127.0.0.1:60000');

eventSource.onopen = function (event) {
  console.log('Connection opened.');
};

eventSource.onmessage = function (event) {
  const eventData = JSON.parse(event.data);
  console.log('Received event data:', eventData);
};

eventSource.onerror = function (event) {
  if (event.eventPhase === EventSource.CLOSED) {
    console.log('Connection was closed.');
  } else {
    console.error('Error occurred:', event);
  }
};
取消断线重连
const eventSource = new EventSource('http://127.0.0.1:60000');

eventSource.onopen = function (event) {
  console.log('Connection opened.');
};

eventSource.onmessage = function (event) {
  const eventData = JSON.parse(event.data);
  console.log('Received event data:', eventData);
};

eventSource.onerror = function (event) {
  if (event.eventPhase === EventSource.CLOSED) {
    console.log('Connection was closed.');
    // 关闭连接,防止自动重连
    eventSource.close();
  } else {
    console.error('Error occurred:', event);
  }
};

http://www.kler.cn/a/576756.html

相关文章:

  • git的坑
  • 【运维篇】KubeSphere-02(经验汇总)
  • 开启焊接设备安全管控新纪元
  • Flask项目框架
  • 手机屏幕摔不显示了,如何用其他屏幕临时显示,用来导出资料或者清理手机
  • Springboot 启动流程
  • uniapp+node+mysql接入deepseek实现流式输出
  • P8748 [蓝桥杯 2021 省 B] 时间显示
  • VS大型CPP项目调试,Debug模式,Release模式,附加到进程模式
  • app测试|面试常问工作常用的adb命令集
  • IBUF和BUFG
  • DeepSeek如何变现?完整版学习资料合集【可下载】
  • 【开题报告+论文+源码】基于SSM的宿舍管理系统的设计与实现
  • 2025网络安全工程师:软考新挑战与职业发展探析
  • python用户图形界面pygtk库安装与使用
  • 代码随想录 回溯
  • 高速率高耐压国产CAN FD芯片技术特性与应用前景
  • TON基金会确认冠名赞助2025香港Web3嘉年华,并将于4月8日重磅呈现“TON生态日”
  • 广度优先遍历(BFS):逐层探索的智慧
  • 大模型开发(五):P-Tuning项目——新零售决策评价系统(二)