1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.前端文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试消息推送</title>
</head>
<body>
<div id="text"></div>
<script>
let source = null;
if (window.EventSource){
// 设置服务器推送消息地址
source = new EventSource('/sse/message');
// 建立连接
source.addEventListener('open',function (e){
console.log("建立连接..")
},false);
// 收到服务端的数据
source.addEventListener('message',function (e) {
console.log("收到服务器的数据:"+e.data)
document.getElementById('text').innerText = e.data
})
}else{
console.log("您的浏览器不支持SSE");
}
</script>
</body>
</html>
3.服务端
/**
* @author qx
* @date 2023-05-25
* @Descripion: SSE实现服务端发送消息给客户端
*/
@Controller
@RequestMapping("/sse")
public class IndexController {
@GetMapping("/index")
public String toIndex() {
return "index";
}
/**
* 测试发送消息
*/
@RequestMapping(value = "/message", produces = "text/event-stream;charset=UTF-8")
@ResponseBody
public void sendMessage(HttpServletResponse response) {
response.setContentType("text/event-stream");
response.setCharacterEncoding("utf-8");
int i = 0;
while (true) {
try {
Thread.sleep(1000);
PrintWriter pw = response.getWriter();
//注意返回数据必须以data:开头,"\n\n"结尾
pw.write("data:未读消息加" + i + "\n\n");
pw.flush();
//检测异常时断开连接
if (pw.checkError()) {
System.err.println("客户端断开连接");
return;
}
} catch (Exception e) {
e.printStackTrace();
}
i++;
}
}
}
4.执行结果 浏览器页面数据一直在实时变动