超好用Web服务端主动推送技术SSE

1、前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="msg_from_server"></div>
<div id="sse"></div>

<script>
    // var sse = new EventSource("http://127.0.0.1:8080/sse")
    var sse = new EventSource("http://127.0.0.1:8080/sse-retry")
    sse.onmessage = function (evt) {
        var el = document.getElementById("sse");
        el.innerHTML = evt.data;
    }
</script>

</body>
</html>

2、后端代码

@Controller
public class SSEController {

    @RequestMapping(value = "/sse")
    @ResponseBody
    public String getStreamDataImprove(HttpServletResponse httpServletResponse) {
        httpServletResponse.setContentType("text/event-stream");
        httpServletResponse.setCharacterEncoding("utf-8");
        String s = "";
        while (true) {
            s = "data:" + LocalDateTime.now() + "\n\n";
            try {
                PrintWriter printWriter = httpServletResponse.getWriter();
                Thread.sleep(1000L);
                printWriter.write(s);
                printWriter.flush();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(value = "/sse-retry")
    @ResponseBody
    public void getStreamDataImprove1(HttpServletResponse httpServletResponse) throws IOException {
        httpServletResponse.setContentType("text/event-stream");
        httpServletResponse.setCharacterEncoding("utf-8");
        String s ="retry:2000\n";
        s+="data:"+LocalDateTime.now()+"\n\n";
        PrintWriter printWriter = httpServletResponse.getWriter();
        printWriter.write(s);
        printWriter.flush();
    }
}
posted @ 2022-11-05 21:11  xl4ng  阅读(165)  评论(0编辑  收藏  举报