SSE and WebSocket usage and comparison, ssewebsocket usage
In our daily development, we will encounter communication between the server and the client. Today we will compare the usage of the HTML5 new features SSE and WebSocket.
I. SSE Introduction
Server-Sent Events (Server-send Events) is an API or mode launched around read-only Comet interaction.
The sse api allows web pages to obtain server updates (HTML5). It is used to create a one-way connection to the server. The server can send any amount of data through this connection. The MIME type of the server response must be text/event-stream, and the JavaScript API in the browser can parse the format output. SSE supports short polling, long polling, and HTTP streams, and automatically determines when to reconnect when the connection is disconnected.
Client
// Determine whether SSEif ('eventsource' in window) {// initialize SSEvar url = "http: localhost: 8080/test/push "; var source = new EventSource (url); // call source when enabling. onopen = (event) => {console. log ("enable SSE");} // listens to the message event source. onmessage = (event) =>{ var data = event. data; $ ("body "). append ($ ("<p> "). text (data);} // listen to the like event source. addEventListener ('like', function (event) {var data = event. data; $ ("body "). append ($ ("<p> "). text (data) ;}, false); // call source when an exception occurs. onerror = (event) => {console. log (event );}
The client only needs to directly use the ** window. EventSource ** object and then call the corresponding method of the object.
Server
/*** SSE background controller * @ author like **/@ Controller @ RequestMapping (value = "/test ") public class TestSSEController {@ ResponseBody @ RequestMapping (value = "/push", produces = "text/event-stream; charset = UTF-8") public String push (HttpServletResponse res) {res. setHeader ("Access-Control-Allow-Origin", "*"); Date date = new Date (); SimpleDateFormat sdf = new SimpleDateFormat ("YYYY-MM-dd HH: mm: ss "); String nowDate = sdf. format (date); return "data: I am a data current time is" + nowDate + "\ nevent: like \ n retry: 5000 \ n ";}}
Because SSE is an http request but is limited to a persistent connection, you must set the MIME type to text/event-stream. Returns a string.
Message format
SSE data sent by the server to the browser must be UTF-8-encoded text;
Each message is composed of several messages, separated by \ n. Each message is composed of several lines;
Format
[field]:value\n
The field can be of four types.
Data indicates the data, event indicates the event name, id indicates the id, and retry indicates the number of training times.
Therefore, the messages written by my server can be translated as: the event name is ** like **, and the data is ** I am a data, the current time is + current time **, round training every 5 seconds
Data: I am a data current time is "+ nowDate +" \ nevent: like \ n retry: 5000 \ n
Below is the message receiving:
2. Websocket
Introduction
WebSocket is a full-duplex communication protocol provided by html5.
Client
Var websocket = null; // determines whether the current browser supports WebSocketif ('websocket 'in window) {WebSocket = new websocket ("ws: // localhost: 8080/WebSocketTest/websocket ");} else {alert ('current browser Not support websocket ')} // callback method websocket in case of a connection error. onerror = function () {setMessageInnerHTML ("WebSocket connection error") ;}; // callback method websocket established successfully. onopen = function () {setMessageInnerHTML ("WebSocket connection successful");} // callback method websocket for receiving messages. onmessage = function (Event) {setMessageInnerHTML (event. data);} // callback Method for closed connections websocket. onclose = function () {setMessageInnerHTML ("WebSocket Connection closed");} // listener window close event. When the window is closed, actively close websocket connection, to prevent the window from being closed before the connection is closed, the server will throw an exception. Window. onbeforeunload = function () {closeWebSocket ();} // display the message on the webpage. function setMessageInnerHTML (innerHTML) {document. getElementById ('message '). innerHTML + = innerHTML + '<br/>';} // disable WebSocket connection function closeWebSocket () {websocket. close () ;}// send message function send () {var message = document. getElementById ('text '). value; websocket. send (message );}
You can see that the client can directly call the ws address.
Server
/*** Websocket service ** @ author like **/@ ServerEndpoint ("/websocket") public class WebsocketTest {private static int onlineCount = 0; // record the current number of online users // ensure thread security private static CopyOnWriteArraySet <WebsocketTest> webSocketSet = new CopyOnWriteArraySet <WebsocketTest> (); private Session session Session; @ OnOpenpublic void onOpen (session Session) {this. session = session; webSocketSet. add (this); addOnlineCount (); System. out. println ("a new connection is added! The current number of online users is "+ getOnlineCount ();} @ OnClosepublic void OnClose () {webSocketSet. remove (this); // Delete subOnlineCount () from the set; // online count minus 1System. out. println ("a connection is closed! The current number of online users is "+ getOnlineCount ();} @ OnMessagepublic void OnMessage (String message, Session session) {System. out. println ("message from client:" + message); // send group message for (WebsocketTest item: webSocketSet) {try {item. sendMessage (message);} catch (IOException e) {e. printStackTrace (); continue ;}}@ OnErrorpublic void OnError (Session session, Throwable error) {System. out. println ("error occurred"); error. printStackTrace ();} public void sendMessage (String message) throws IOException {this. session. getBasicRemote (). sendText (message); // this. session. getAsyncRemote (). sendText (message);} public static synchronized int getOnlineCount () {return onlineCount;} public static synchronized void addOnlineCount () {WebsocketTest. onlineCount ++;} public static synchronized void subOnlineCount () {WebsocketTest. onlineCount --;}}
Demo
Background output:
A new connection is added! Currently, the number of online users is 1 message from the client: 123 message from the client: 456
Iii. Summary
SSE and WebSocket have similar functions and are used to establish communication channels between browsers and servers. The difference between the two is:
- WebSocket is a full-duplex channel that supports two-way communication and is more powerful. SSE is a one-way channel and can only be sent from the server to the browser.
- WebSocket is a new protocol that requires server support. SSE is deployed on the HTTP protocol and is supported by existing server software.
- SSE is a lightweight protocol, which is relatively simple; WebSocket is a heavier protocol, which is relatively complex.
- SSE supports reconnection by default, and WebSocket requires additional deployment.
- SSE supports Custom Data Types for sending.
- SSE does not support the CORS parameter. The url is the server url. It must be in the same domain as the current webpage, and the protocol and port must be the same.