SSE
2024年11月17日大约 1 分钟
概念
SSE(Server - Sent - Events):服务器发送事件
这种模式跟WebSocket相像,只不过跟它不相同的地方在于
- ws是全双工协议,可以双方通信。SSE是单向通道,只能服务器向游览器发送
- ws是新协议,需要服务端的支持。SSE是建立在HTTP协议之上的
- ws是一种较重的协议,很复杂。SSE是一种轻量级协议
- SSE支持短线重连,ws则需要额外部署
- SSE支持自定义发送的数据类型

返回消息的格式:data: 消息 \n\n
;\n
是个转义字符代表换行
两种应用模式
客户端:
let eventSource = new EventSource('替换为SSE服务端点');
eventSource.addEventListener('message', (event) => {
const messageData = event.data;
// 使用返回数据
});
以下均为服务器端
服务器流式推送
@RestController
@RequestMapping("system")
public class SystemController {
@GetMapping("resourceInfo")
public void resourceInfo(HttpServletResponse response) throws IOException, InterruptedException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
while (true) {
PrintWriter pw = response.getWriter();
pw.write("data: " + new Date() + "\n\n");
pw.flush();
}
}
}
服务器重连推送
@RestController
@RequestMapping("system")
public class SystemController {
@GetMapping("resourceInfo")
public void resourceInfo(HttpServletResponse response) throws IOException, InterruptedException {
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
// 这次没有循环,但是客户端在接收到数据后未来的两秒内没有在收到新的数据会重新尝试请求这个接口
PrintWriter pw = response.getWriter();
pw.write("retry: 2000\ndata: " + new Date() + "\n\n");
pw.flush();
}
}