HTML5 data push SSE principle and application development

JavaScript expresses behavior, and CSS expresses appearance. Note that HTML expresses both structure (logical structure) and content (data itself). Usually when the data needs to be updated, the structure does not need to be updated. This is exactly the desire to change the data without changing the organizational structure. , promoting the emergence of data pull and data push technologies.

SSE is an HTML5 technology that allows the server to push new data to the client (referred to as data push). There are two alternatives to data push: no updates and data pull.

No update plan:

After loading the HTML, you get an HTML page, and then the browser will request images, CSS files, JavaScript files, etc. They are all static files that the browser can cache. If the page uses a back-end language, such as PHP, Ruby, Python and other languages ​​that dynamically generate HTML for users.

Data pull plan:

The browser will request or completely update data from the server based on some user behavior, or after a certain period of time, or based on some other trigger scheme. The entire page can be ordered to reload through javascript or a meta tag. The familiar Ajax technology is only used to request the latest data. When the data is received, the javascript function will use it to locally update the DOM. The essence of data pulling: only pull new data, and only update the affected parts of the page .

None of the above is data push. Data push is not a static file, nor does it involve the browser initiating a request to update data. Data push is when the server selects the client to send new data.

When the data source has new data, the server can immediately send it to one or more clients without waiting for the client to request it. The new data may be breaking news, the latest stocks, chat messages from online friends, or new weather. Forecasts, next steps in strategy games, and more.

SSE is suitable for frequent updates, low latency and data from the server to the client. The difference between it and WebSocket:

1) Convenience. There is no need to add any new components. You can continue to use it with any back-end language and framework you are used to. There is no need to worry about getting a new IP or a new port number for a new virtual machine.

2) Server-side simplicity. Because SSE operates on existing HTTP/HTTPS protocols, it can run directly on existing proxy servers and authentication technologies.

The biggest advantage of WebSocket over SSE is that it is a two-way communication, which means that sending data by the server is as simple as receiving data from the server, while SSE generally transmits data from the client to the server through an independent Ajax request, so compared to Using Ajax with WebSocket adds overhead. Therefore, if you need to transmit data to the server once per second or faster, you should use WebSocket.

The specific code is as follows:

html code

<!doctype html><html>
    <head>
        <meta charset="UTF-8">
        <title>basic SSE test</title>
    </head>
    <body>
        <pre id = "x">initializting...</pre>
        <!--The reason why the pre tag is used instead of p or div is to ensure that the data can be presented in the format in which it was received, without modification or formatting-->

    </body>
    <script>
        var es = new EventSource("basic_sse.php");
        es.addEventListener("message",function(e){            //e.data
            document.getElementById("x").innerHTML += "\n"+e.data;
        },false);//Use false to indicate that the event is processed in the bubbling phase rather than the capturing phase.
    </script></html>

It should be noted that it is best to check before using server-side data to prevent potential JavaScript injection attacks.

php code

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');
    $time = date('r');    echo "data: The server time is: {$time}\n\n";
    flush();?>

"Content-Type: text/event-stream" is a MIME type specially designed for SSE.

Effect screenshot

When is data push the wrong choice?

First consider the static situation, without introducing data push. Whenever the user opens a page, a socket connection will be opened between the browser and the server. The server phone information is then returned to the user. It may be as simple as from Loading a static HTML file or image on disk can be as complex as running a background language that connects to many databases. The key point here is that once the required information is returned, the socket is closed and each HTTP request opens one of these relatively short-lived socket connections, which are limited on the server. Resources, whenever they complete their intended tasks, are recovered for recycling.

Now let’s compare data push. A request never completes, there is always a lot of information to send, so the socket remains open . Obviously, because they are limited resources, there will be a limit to the number of SSE connections at the same time.

Imagine a situation where you are providing telephone support for your latest application. You have 10 call center employees serving 1,000 users. A user encounters a problem and one of the operators picks up the line and then hangs up. New customer calls are queued until one of the operators hangs up, which is a typical network service pattern.

However, now a customer called and said, I don't have a problem now, but I will be using your product in the next few hours, and if I encounter a problem, I hope you will respond immediately. This customer will stay on the phone with the operator for several hours, and 10% of the call center's service resources are wasted. If there are 10 such customers, then the other 990 customers cannot call. This is the data push model.

Of course, this is not always a bad thing. If this customer has a problem every few seconds throughout the afternoon, keeping the phone open in this situation will not waste 10% of service resources, but will increase it. Because each question requires a new call (like a data pull), the operator needs to spend extra time verifying the customer's identity and pulling up accounts, reducing service efficiency. Staying on the phone usually not only makes customers more satisfied, but also improves the efficiency of the call center. This is the most suitable scenario for data push.

Guess you like

Origin blog.csdn.net/delishcomcn/article/details/132963395