Java Spring使用event-stream进行数据推送

时间:2024-03-27 20:40:33

前端使用EventSource方式向后台发送请求,后端接收到之后使用event-stream方式流式返回。可以应用在时钟、逐字聊天等场景。

前端js示例代码(向后台请求数据,并展示到“id=date”的div上)

<script type="text/javascript">
    if (typeof (EventSource) !== "undefined") {
        var eventSource = new EventSource("${root}/test/getDate");
        eventSource.onmessage = function (event) {
            document.getElementById("date").innerHTML = event.data;
        }
        eventSource.addEventListener('error', function (event) {
            console.log("错误:" + event);
        });
        eventSource.addEventListener('open', function (event) {
            console.log("建立连接:" + event);
        });
    } else {
        document.getElementById("date").innerHTML = "抱歉,您的浏览器不支持EventSource事件 ...";
    }
</script>

后端java示例

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

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Controller
@RequestMapping(value = "/test")
public class TestController {

    @ResponseBody
    @RequestMapping(value = "/getDate", produces = "text/event-stream;charset=UTF-8")
    public void getDate(HttpServletResponse response) throws Exception {
        System.out.println("getDate event start");
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(200);
        for (int i = 0; i < 10; i++) {
            response.getWriter().write("data:" + new Date() + "\n\n");
            response.getWriter().flush();
            Thread.sleep(1000);
        }
        response.getWriter().close();
        System.out.println("getDate event end");
    }

}

相关文章