SSE
2025/11/7大约 1 分钟hyperlanewebrustusage-introductionsse
提示
hyperlane 框架支持 sse,服务端主动推送,下面是每隔 1s 完成一次推送,并在 10 次后关闭连接。
提示
sse 规范: 服务器使用 "content-type: text/event-stream" 表示响应是一个 sse 事件流。 接着使用 "data" 字段来发送事件数据,每个事件以 "data:" 开头,后面跟着事件的内容和一个空行。 客户端收到这样的响应后,就可以解析其中的事件数据并进行相应的处理。 如果开发者非首次响应尝试调用 send 会正常发送响应,但是会包含整个 http 协议内容,所以对于 sse, 非首次响应请统一使用 send_body 方法。
服务端代码
struct SseRoute;
impl ServerHook for SseRoute {
async fn new(_ctx: &Context) -> Self {
Self
}
async fn handle(self, ctx: &Context) {
let _ = ctx
.set_response_header(CONTENT_TYPE, TEXT_EVENT_STREAM)
.await
.send()
.await;
for i in 0..10 {
let _ = ctx
.set_response_body(&format!("data:{}{}", i, HTTP_DOUBLE_BR))
.await
.send_body()
.await;
}
let _ = ctx.closed().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);
}
};