Java SSE流式数据前后端实现
#Java SSE流式数据前后端实现
Java后端实现
@RestController
public class SSEController {
@GetMapping(value = "/sse/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter streamSse() throws InterruptedException, IOException {
SseEmitter emitter = new SseEmitter(60_000L);
new Thread(() -> { // 异步通信,否则消息会全部完成后发送
try {
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000); // 模拟延迟
emitter.send("data: Message " + i + "\n\n");
}
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
}
}).start();
return emitter;
}
}
##前端代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE Example</title>
</head>
<body>
<div id="output"></div>
<script>
const output = document.getElementById('output');
const eventSource = new EventSource('http://localhost:8080/sse/stream');
eventSource.onmessage = function(event) {
console.log(event);
const data = event.data;
const newElement = document.createElement('div');
newElement.textContent = data;
output.appendChild(newElement);
};
eventSource.onerror = function(e) {
console.error('SSE Connection Error:', e);
eventSource.close();
const newElement = document.createElement('div');
newElement.textContent = "Connection Closed";
output.appendChild(newElement);
};
</script>
</body>
</html>