1. What is SSE
Strictly speaking,HTTP protocolThe server cannot actively push information. However, there is a workaround, which is to declare to the client that the next thing to send is streaming.
In other words, what is sent is not a one-time data packet, but a data stream that will be sent continuously. At this time, the client will not close the connection and will wait for the new data stream sent by the server. Video playback is such an example. In essence, this kind of communication is to complete a long download in a stream of information.
SSE uses this mechanism to push information to the browser using streaming information. It is based on the HTTP protocol and currently supports it except IE/Edge.
2. How to implement SSE in java
In Spring Boot projects, no additional specific dependencies need to be introduced, as the Spring Web MVC module already has SSE support built-in.
1. Write an SSE service to create links and send messages
package com.; import .slf4j.Slf4j; import .; import ; import ; import ; import ; import ; @Slf4j @Service public class SSEService { private static final Map<String,SseEmitter> sseEmitterMap = new ConcurrentHashMap<>(); public SseEmitter crateSse(String uid) { SseEmitter sseEmitter = new SseEmitter(0L); (() -> { ("[{}]End link" , uid); (uid); }); (() -> { ("[{}]Link timeout",uid); }); (throwable -> { try{ ("[{}]Link exception,{}",uid,()); (() .id(uid) .name("Exception occurred") .data("Please try again if an exception occurs") .reconnectTime(3000)); (uid,sseEmitter); }catch (IOException e){ (); } }); try{ (().reconnectTime(5000)); }catch (IOException e){ (); } (uid,sseEmitter); ("[{}]createsseConnection successfully!",uid); return sseEmitter; } public boolean sendMessage(String uid,String messageId,String message){ if((message)){ ("[{}]Parameter exception,msgEmpty",uid); return false; } SseEmitter sseEmitter = (uid); if(sseEmitter == null){ ("[{}]sseThe connection does not exist",uid); return false; } try{ (().id(messageId).reconnectTime(60000).data(message)); ("user{},informationID:{},Push successfully:{}",uid,messageId,message); return true; }catch (IOException e){ (uid); ("user{},informationID:{},information推送失败:{}",uid,messageId,message); (); return false; } } public void closeSse(String uid){ if((uid)){ SseEmitter sseEmitter = (uid); (); (uid); }else { ("user{}The connection is closed",uid); } } }
2. Write the corresponding controller to implement specific business
package ; import ; import ; import ; import ; import .*; import ; @Controller @RequestMapping("test") public class TestController { @Autowired private SSEService sseService; @GetMapping("createSse") @CrossOrigin public SseEmitter createSse(String uid) { return (uid); } @GetMapping("sendMsg") @ResponseBody @CrossOrigin public String sseChat(String uid){ for (int i = 0; i < 10; i++) { (uid,"information"+i,().replace("-","")); } return "OK"; } @GetMapping("closeSse") @CrossOrigin public void closeSse(String uid){ (uid); } }
3. Front-end implementation of message monitoring
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>SSEMessage push listening</title> </head> <body> <div ></div> <script> let uid = 1; let chat = ("conMsg"); if(){ var eventSource = new EventSource(`http://127.0.0.1:8090/test/createSse?uid=${uid}`); = ()=>{ ("Link Success"); } = (ev)=>{ if(){ += +"<br>"; } } = ()=>{ ("Sse link failed") } }else{ alert("The current browser does not support sse") } </script> </body> </html>
This is the end of this article about Java's message push through SSE. For more related Java SSE message push content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!