需求
实现方式
SSE案例(Springboot项目)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController
@RequestMapping("/sse")
public class SseController {
@RequestMapping(value = "/get_data", produces = "text/event-stream;charset=UTF-8")
public String push() throws InterruptedException {
Thread.sleep(1000);
return "data:测试数据:" + Math.random() + "\n\n";
}
}
- resource目录下创建public目录,然后创建index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
let source = new EventSource("http://localhost:8080/sse/get_data");
source.addEventListener('message',function (t){
var data = t.data;
document.getElementById("result").innerText = data;
})
source.addEventListener('open', function(e) {
console.log("连接打开.");
}, false);
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("连接关闭");