SSE(Server Send Event 服务端发送事件)

原创
2018/08/17 00:22
阅读数 1.8K
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * SSE(Server Send Event 服务端发送事件) 的服务端推送,需要新式浏览器
 */
@Controller
public class SeeController {


    /**
     * 5秒向浏览器发送数据
     *
     * @return
     * @throws InterruptedException
     */
    @RequestMapping(value = "/push", produces = "text/event-stream")
    @ResponseBody
    public Object push() throws InterruptedException {

        TimeUnit.SECONDS.sleep(5);

        String msg = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
        //固定格式
        return "data:" + msg + "\n\n";
    }


}

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello
<script type="text/javascript">

    if (!!window.EventSource) {

        var source = new EventSource('push');

        //打开连接
        source.addEventListener('open', function (evt) {
            // console.info("连接已经打开了");
        }, false);


        //接收消息
        source.addEventListener('message', function (evt) {
            console.info(evt.data);
        });

        //错误消息,及关闭通知
        source.addEventListener('error', function (evt) {
            // console.info(evt);
        }, false);

    } else {
        alert("浏览器不支持 SSE")
    }

</script>
</body>
</html>

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部