Server-Sent Events (HTML5 Server send event), server-senthtml5

Source: Internet
Author: User

Server-Sent Events (HTML5 Server send event), server-senthtml5
Introduction to Server-Sent Events

Server-Sent Events (SSE) is used to automatically obtain updated data on the Server on a webpage. It is a real-time mechanism.

Real-time data acquisition Solution

For some data that needs to be updated in real time (such as Facebook/Twitter updates, valuation updates, new blog posts, and event results), there are several solutions:

Polling)

The client repeatedly sends new requests to the server. If no new data changes on the server, close the connection. Then, the client initiates a new request after a while and repeats this step.

Long-polling)

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

Server-Sent Events

SSE is similar to the long polling mechanism, but in each connection, it not only waits for a data change. The client sends a request to the server. The server keeps the request until a new message is ready and returns the message to the client. If the connection is not closed, the request is still used by other messages. One feature of SSE is to repeat a connection to process each message (also called event ).

WebSocket

WebSocket is different from the above technologies because it provides a real two-way connection. WebSocket is a powerful new feature in HTML5 and has been widely used. (Do not expand it here)

 

A basic example: Dynamic Update Time (based on Servlet)

We hope to display a dynamic change time in the html page. Here we use Server-Sent Events to implement it, get the time in the background, and send it to the front-end continuously.

<!DOCTYPE html>

This is a very simple HTML page. Combined with JS code, we want to change the value in the <span id = "foo"> </span> label, which is the most pure purpose. The following code is analyzed:

1. A new EventSource object is used to request service interruption. In its constructor, a request URL is required to request the Servlet/Action...

2. Use the onmessage function of the EventSource object to obtain the data transmitted by the server.

Analyze the backend code:

Public class HelloServlet extends HttpServlet {@ Override public void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// ContentType must be specified as text/event-stream resp. setContentType ("text/event-stream"); // CharacterEncoding must be specified as a UTF-8 resp. setCharacterEncoding ("UTF-8"); PrintWriter pw = resp. getWriter (); for (int I = 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 ();}}

We can see that the back-end code is actually a common Servlet (Web. xml omitted), overwrites the Get method, and writes messages using the PrintWriter obtained by the response object. This is a general idea.

1. Set ContentType to text/event-stream

2. Set CharacterEncoding to UTF-8

3. Get the PrintWriter object and write data. The format is data: xxxx \ n. Note that there must be two \ n as the end.

This tells the client that I sent the data in event-stream format encoded as a UTF-8, with the data length as follows:

Data: xxxx \ n

Then the client's JS Code uses the onmessage function of the EventSource object to listen to the server's data changes and parse the content xxxx, that is, event. data = xxxx;

 

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.