天天看點

java sse執行個體_SSE(Server Send Event 服務端發送事件)

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;

@Controller

public class SeeController {

@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";

}

}

Title

hello

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")

}

轉載至連結:https://my.oschina.net/u/2552286/blog/1929292