HTML5 Server push Events, html5server-sent
Server-sent Events (Server-sent Events) is a one-way communication protocol based on WebSocket protocol that allows a Server to send Events and data to a client. Currently, all mainstream browsers support sending events to servers, except Internet Explorer. 2333...
WebSocket is another Server Client Communication Protocol following the HTTP protocol. different from the one-way communication mode in which the HTTP client requests the server to respond, WebSocket supports two-way communication between the Server Client.
Use of Server-sent Events
Server-sent Events (SSE) as the Server => client communication method, the client must have the corresponding service address and response method, and the Server must have the corresponding data transmission method; let's talk about the code!
Client JS Code
Add the following JS Code to the H5 page: <script> if (typeof (EventSource )! = "Undefined") {// PUSH Service Interface address var eventSource = new EventSource (" http://localhost:2242/webservice/ServerSent/SentNews "); // When the connection to the server is enabled eventSource. onopen = function () {console. log ("connection opened... ");} // when an error occurs eventSource. onerror = function (e) {console. log (e) ;}; // when a message is received, this event is the default event eventSource. onmessage = function (event) {console. log ("onmessage... "); eventSource. close () // close SSE link}; // server pushes sentMessage event eventSource. addEventListener ('sentmessage', function (event) {var data = eval ('+ event. data + '); // The data pushed by the server, eval Json object var origin = event. origin; // The domain name of the server URL, that is, the Protocol, domain name, and port, indicating the message source. Var lasteven tid = event. lasteven tid; // the ID of the data, which is sent by the server. If there is no number, this attribute is blank. // Write the business logic console as needed. log (data) ;}, false) ;}else {// the browser does not support server-sent events. All mainstream browsers support server event sending, except Internet Explorer. Document. getElementById ("result"). innerHTML = "Sorry, your browser does not support server-sent events..." ;}</script>
Server
What data format should the server return? What kind of response should be made to the client? First, let's take a. Net example.
/// <Summary> /// push the message /// </summary> /// <returns> </returns> [HttpGet] public HttpResponseMessage SentNews () {HttpResponseMessage response = Request. createResponse (HttpStatusCode. OK); try {// response. headers. add ("Access-Control-Allow-Origin", "*"); // you can configure string data_str = "push to client data" for cross-domain requests "; // of course, it can be a json string format string even = "", data = ""; if (! String. isNullOrWhiteSpace (data_str) {even = "event: sentMessage \ n"; data = "data:" + data_str + "\ n";} string retry = "retry: "+ 1000 +" \ n "; // the reconnection time after disconnection (in milliseconds) can be understood as the polling time of 2333... byte [] array = Encoding. UTF8.GetBytes (even + data + retry); Stream stream_result = new MemoryStream (array); response. content = new StreamContent (stream_result); response. content. headers. contentType = new MediaTypeHeaderValue ("text/event-stream"); // You must configure response here. headers. cacheControl = new CacheControlHeaderValue (); response. headers. cacheControl. noCache = false;} catch (Exception ex) {LogHelper. writeWebLog (ex);} return response ;}
After reading the above code, I think you should have a rough idea. The response method is HTTPResponse response, but there is always a small requirement:
- Response Header "Content-Type" to be set to "text/event-stream"
The response data format should also note the "data:", "event:", and "retry:" tags in the above Code:
The above isServer-sent EventsI will not demonstrate the implementation results of simple applications. If you are interested, you can perform operations to achieve the results in person!