服务端给 sse 消息加上递增的 id。eventsource 重连时会通过 last-event-id 发送上次接收的位置,服务端读取该值并补发之后的事件。

让服务器按连接传来的位置重放
保存为 server.js。这个同源演示使用固定的三条消息,初次连接只发送前两条,随后结束响应。
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const events = ['任务已建立', '任务处理中', '任务已完成'];
const page = fs.readFileSync(path.join(__dirname, 'index.html'));
http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(page);
}
if (req.url !== '/events') {
res.writeHead(404);
return res.end();
}
const header = req.headers['last-event-id'];
const cursor = Number(header || '0');
if (!Number.isInteger(cursor) || cursor events.length) {
res.writeHead(400);
return res.end();
}
if (cursor === events.length) {
res.writeHead(204);
return res.end();
}
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache',
});
res.write('retry: 500\n\n');
const limit = header ? events.length : 2;
for (let i = cursor; i <p><img src="https://img.php.cn/upload/image/825/995/244/1794899235699855.jpg?x-oss-process=image/resize,p_40" alt=""></p><p>每条消息以空行分隔。正式服务可以用事件表或消息日志查询游标之后的记录,避免把所有连接的进度存在一个全局变量里。</p><h2>浏览器显示事件 ID 并在完成后关闭</h2><p>保存为同目录的 index.html。连接异常时显示状态,让浏览器按内置机制重连。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build Java agent transport gateways with Atmosphere" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere" class="overflowclass">Build Java agent transport gateways with Atmosphere</a>
<p class="overflowclass">使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><pre class="brush:php;toolbar:false;">
<meta charset="utf-8"><p id="status" role="status"></p>
预期依次展示 ID 1、2、3,各出现一次。主动调用 close() 会终止重连。
从网络记录确认游标
运行 node server.js,打开 http://127.0.0.1:3000/。也可以用下面两条命令分别观察服务端的初次响应和续传响应。
curl -Ns http://127.0.0.1:3000/events curl -Ns -H 'Last-Event-ID: 2' http://127.0.0.1:3000/events
第一条返回两条消息,第二条只返回 ID 3。浏览器发送的是传输游标。如果应用需要在业务处理成功后才确认位置,应另外记录业务进度与去重键。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










