Server-sent Events (HTML5 server send event)

Source: Internet
Author: User

About Server-sent Events

Server-sent Events (SSE) is a real-time mechanism for Web pages to automatically get updated data on the server.

Real-time access to data solutions

There are several solutions for some data that need to be updated in real time (such as facebook/twitter updates, valuation updates, new posts, event results, etc.):

Polling (polling)

The client repeatedly sends a new request to the server. If the server does not have new data changes, close this connection. The client then repeats the new request again after a short period of time, repeating this step.

Long-polling (Long poll)

In long polling, the client sends a request to the server. If there are no new data changes on the server, the connection will be persisted until the updated data is returned to the client and the connection is closed.

Server-sent Events

SSE is similar to a long polling mechanism, but it is not only waiting for data changes in each connection. The client sends a request to the server, and the server keeps the request until a new message is ready, returns the message to the client, does not close the connection, and still retains it for other messages to use. One of the features of SSE is that it reuses a connection to process every message (aka event).

WebSocket

WebSocket differs from these techniques because it provides a true two-way connection. WebSocket is a very powerful new feature in HTML5 and has been widely used. (Not for the time being expanded here)

A basic example--Dynamic update time (Servlet-based)

We want to display a dynamically changing time in the HTML page, which is implemented using Server-sent events, which gets time in the background and is constantly sent to the foreground.

<!DOCTYPE HTML><HTML><Head><MetaCharSet= "UTF-8"><title>Insert Title here</title>    <Script>        functionstart () {varEventSource= NewEventSource ("HelloServlet"); Eventsource.onmessage= function(event) {document.getElementById ("Foo"). InnerHTML=Event.data;        }; }    </Script></Head><Body>Time :<spanID= "Foo"></span>        <BR><BR>    <Buttononclick= "Start ()">Start</Button></Body></HTML>

This is a very simple HTML page, combined with JS code, we now want to change the value of <span id= "foo" ></span> tag, which is the purest purpose. The following analysis code:

1.new out a EventSource object, this object is used to request the service broken, its construction method requires a request URL, to request which servlet/action, etc...

2. Use the OnMessage function of the EventSource object to get the data passed by the server.

Then analyze the backend code:

 Public classHelloServletextendsHttpServlet {@Override Public voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {//ContentType must be specified as Text/event-streamResp.setcontenttype ("Text/event-stream"); //characterencoding must be specified as UTF-8Resp.setcharacterencoding ("UTF-8"); PrintWriter PW=Resp.getwriter ();  for(inti=0; i<10; i++) {            //each message sent must end with \ n
Pw.write ("Data:" + system.currenttimemillis () + "\ n")); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }} pw.close (); }}

As can be seen here, the backend code is actually a common servlet (web. xml omitted), rewrite the Get method, use the response object to get the PrintWriter to write the message, this is a general idea.

1. Set ContentType to Text/event-stream

2. Set Characterencoding to UTF-8

3. Get PrintWriter object, write data, format: data:xxxx \ n \ nyou must have two.

This tells the client: I sent the event-stream format and encoded as UTF-8 data, the data length is as follows:

DATA:XXXX \ n

Then the client's JS code uses the EventSource object's OnMessage function, the supervisor hears the service side's data change, parses the content xxxx, namely event.data = xxxx;

Server-sent Events (HTML5 server send event)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.