SseEmitter推送
后端代码SseController.java
package com.theorydance.mywebsocket.server; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder; import lombok.extern.slf4j.Slf4j; @CrossOrigin @RestController @Slf4j public class SseController { private Map<String,SseEmitter> emitterMap = new HashMap<>(); public SseController() { log.info("init sseController"); } @GetMapping("/getData") public SseEmitter getData(@RequestParam String id){ final SseEmitter emitter = new SseEmitter(); emitter.onCompletion(() -> { emitterMap.remove(id); log.info("onCompletion"); }); emitter.onError(e -> { emitterMap.remove(id); log.info("onError:" + e.getMessage()); }); emitter.onTimeout(() -> { emitterMap.remove(id); log.info("onTimeout"); }); try { emitterMap.put(id,emitter); }catch (Exception e){ emitter.completeWithError(e); } return emitter; } @GetMapping("/payback") public String payback(@RequestParam String id){ SseEmitter emitter = emitterMap.get(id); String res = "推送失败,已关闭"; if(emitter != null){ try { String uuid = UUID.randomUUID().toString(); SseEventBuilder builder = SseEmitter.event().data(uuid); emitter.send(builder); res = "ok"; } catch (Exception e) { e.printStackTrace(); } } return res; } }
前端代码:
<body> <script> /** * H5 EventSource 实现web页面推送功能demo */ var serverData,statusDiv; var SERVER_URL = "http://localhost:8080/demo/getData?id=11"; //servers Url Adress window.onload = function(){ startlistenServer(); } function startlistenServer(){ var es = new EventSource(SERVER_URL); //es.addEventListener("newDate",newDateHandler); es.onopen =openHandler; es.onerror = errorHandler; es.onmessage = messageHandler; } function openHandler(e){ console.log('openHandler'); } function errorHandler(e){ console.log('errorHandler'); } function messageHandler(e){ console.log(e.data); } function newDateHandler(e){ serverData.innerHTML = e.data; } </script> </body>
后面贴一个图,我自己的总结,如果发现什么不对的描述,请留言