1.What is SSE?
SSE (Server-Sent Events) is a technology used to enable servers to actively push data to clients, also known as "event stream". It is based on the HTTP protocol, which takes advantage of its long connection feature to establish a persistent connection between the client and the server, and through this connection, the server pushes real-time data to the client.
The basic principles of technology
- The client sends a GET request to the server with a specified header, indicating that the event stream type can be received and any event cache is disabled.
- The server returns a response with a specified header that represents the media type and encoding of the event, and uses chunked transport encoding to stream dynamically generated content.
- When data is updated, the server sends an event composed of one or more name:value fields to the client, separated by a single newline character. Events are separated by two newline characters. The server can send fields such as event data, event type, event ID, and retry time.
- The client uses the EventSource interface to create an object, open a connection, and subscribe to event handlers such as onopen, onmessage, and onerror to handle connection status and receive messages.
- The client can use GET query parameters to pass data to the server, or use the close method to close the connection.
The difference between Socket
SSE (Server-Sent Events) and WebSocket are both technologies that implement servers push data in real time to clients, but they still have certain differences in some aspects.
Technology implementationSSE is based on the HTTP protocol and takes advantage of its long connection feature to send an HTTP request to the server through the browser to establish a persistent connection. WebSocket establishes a new TCP connection through a special upgrade protocol (HTTP/1.1 Upgrade or HTTP/2), which is different from traditional HTTP connections.
Data formatSSE can transmit text and binary format data, but only supports one-way data streams, that is, data can only be pushed by the server to the client. WebSocket supports two-way data flow, and clients and servers can send messages to each other, and there is no message size limit.
Connection statusThere are only three connection statuses of SSE ==: connected, connected, disconnected ==. The connection status is automatically maintained by the browser and the client cannot manually close or reopen the connection. The status of WebSocket connection is more flexible, and can be manually opened, closed, reconnected, etc.
compatibilitySSE is a standard web API that can be used on most modern browsers and mobile devices. However, if you need to be compatible with older versions of browsers (such as IE6/7/8), you need to use the polyfill library for compatibility. WebSocket may have compatibility issues on some older Android phones and needs to be handled using some special APIs.
SecurityThe implementation of SSE is relatively simple, both based on the HTTP protocol, and is not much different from ordinary web applications, so the risk is relatively low. WebSocket needs to use additional security measures (such as SSL/TLS encryption) to ensure the security of data transmission and avoid eavesdropping and tampering, otherwise it may pose security risks.
Overall, SSE and WebSocket have their own advantages and disadvantages, suitable for different scenarios and needs. If only the server needs to push data to the client one-way and apply it in the front-end browser environment, SSE is a lighter, easier to implement and maintain. However, if data transmission is required in two-way, support custom protocols, or be applied in more complex network environments, WebSocket may be more suitable.
SSE is suitable for scenariosSSE applicable scenarios refer to scenarios where the server pushes data to the client in real time, for example:
- Stock price update: The server can push the stock price to the client in real time according to changes in the stock market, so that the client can timely understand the stock trends and market trends.
- Real-time news push: The server can push news content or title to the client in real time according to news updates, so that the client can keep abreast of the latest news and information in a timely manner.
- Online chat: The server can push chat messages to the client in real time according to the user's sending, so that the client can receive and reply messages in a timely manner.
- Real-time monitoring: The server can push monitoring data or alarm information to the client in real time based on the status of the device, so that the client can timely understand the operation and abnormal situations of the device.
The characteristics of SSE applicable scenarios are:
- Frequent data updates: The server needs to continuously push the latest data to the client to maintain the real-time and accuracy of the data.
- Low latency: The server needs to push data to the client as soon as possible to avoid delays and expiration of data.
- One-way communication: The server only needs to push data to the client, but does not need to receive the client's data.
4. Write an SSE service to create links and send messages
Service:
package ; 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); } } }
Controller:
package ; import ; import ; import ; import .*; import ; import ; import ; @Controller @RequestMapping("/aggregate/api/pay") public class TestController { private static final Map<String,Boolean> SEND_MAP = new ConcurrentHashMap<>(); @Autowired private SSEService sseService; @GetMapping("createSse") @CrossOrigin public SseEmitter createSse(String uid) { return (uid); } @GetMapping("/sendMsg") @ResponseBody @CrossOrigin public SseEmitter sendMsg(@RequestParam("uid") String uid) throws InterruptedException { SseEmitter sseEmitter = (uid); if (SEND_MAP.get(uid)==null || !SEND_MAP.get(uid)){ new Thread(()->{ int i=0; while (true){ try { i++; String message = "uid:"+uid+" number:"+i+" message:"+().replace("-", ""); (uid,"information"+i,message); SEND_MAP.put(uid,true); (1000); } catch (InterruptedException e) { (); closeSse(uid); } } }).start(); } return sseEmitter; } @GetMapping("closeSse") @CrossOrigin public void closeSse(String uid){ (uid); } }
5. 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://localhost:9001/aggregate/aggregate/api/pay/sendMsg?interfaceId=CEDB297CECCC9DCBAD348204ACDD5BAD&uid=${uid}`); = ()=>{ ("Link Success"); } = (ev)=>{ if(){ += +"<br>"; } } = ()=>{ ("Sse link failed") } }else{ alert("The current browser does not support sse") } </script> </body> </html>
Summarize
This is the end of this article about how Java can implement 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!