What is the content-type request for text/event-stream?

Recently, when learning the hot update of webpack, we found that there is a _webpack_hmr request, content-type is text/event-stream, which we haven't seen before, so learn to record it.

Web pack hot updates need to push information to browsers, and websocket is usually thought of, but there is another way, called Server-Sent Events (SSE).

SSE is a lightweight alternative to websocket.

It differs from websocket in the following aspects:

  • SSE uses http protocol, while websocket is a separate protocol
  • SSE is a one-way transmission, which can only be pushed from the server to the client, while websocket is a two-way transmission.
  • SSE supports breakpoint continuation and websocket needs to be implemented by itself
  • SSE supports sending custom type messages

Principle of SSE:
It is equivalent to the client launching a download request to the server. Data is not a one-time data package, but a data stream, which is continuously transmitted to the client, similar to video download.

Simple methods of use:
Client:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>SSE Demo</title>
</head>
<body>
    <div id="page"></div>
    <script>
        // SSE API s on EventSource objects
        // You can use if ('EventSource'in window) to determine whether browsers support SSE
        // Establish SSE connections, create EventSource instances directly as follows, support spanning
        var source = new EventSource("http://127.0.0.1:9988/createSse");

        // EventSource.readyState represents the connection state in three cases
        // 0-> Connection has not been established, or is disconnecting and reconnecting
        // 1 - > Connection is established and data is acceptable
        // 2 - > Connection closed or request error

        var div = document.getElementById("page");

        // Connection Creation Successful Callback Events
        source.onopen = function (event) {
            div.innerHTML += "<p>Connection open ...</p>";
        };

        // Callback events for connection creation failure
        source.onerror = function (event) {
            div.innerHTML += "<p>Connection close.</p>";
        };

        // Custom event, Set event Field to Custom event Name when Server Returns
        source.addEventListener("connecttime",
            function (event) {
                div.innerHTML += "<p>Start time: " + event.data + "</p>";
            },
            false
        );

        // Accept callback events for data, and when event is not specifically set, the default is message
        source.onmessage = function (event) {
            div.innerHTML += "<p>message event: " + event.data + "</p>";
        };

        // Close the connection source.close();

    </script>
</body>
</html>

Server:
The data returned by the server must contain the following header s

Content-Type: text/event-steam//Content-Type in the first line must be specified as text/event-steam
Cache-Control: no-cache
Connection: keep-alive

The data returned by the server is composed of several message s, each of which is divided into n\n\ n (because the data format must be text-based).
Each message content is [field]: value n
field has four situations: id, event(type), data, retry

  • The browser reads the id with lastEventId for the unique identification of each returned data. Once the connection is disconnected, the browser will send a new http request with a special request header Last-Event-Id, which represents the id at the time of disconnection. It is used to establish a reconnection and belongs to a reconnection synchronization mechanism.
  • Data data content is generally placed in the data field.
  • event(type): Message type, which is generally defaulted to message, can be customized by the server and monitored by addEventListener() at the front end.
  • retry: The interval between sending requests again on behalf of the server.

Code:

var http = require("http");

http.createServer(function(req, res) {
    if(req.url === '/createSse') {
        res.writeHead(200, {
            "Content-Type": "text/event-stream",
            "Cache-Control": 'no-cache',
            "Connection": 'keep-alive',
            "Access-Control-Allow-Origin": '*'
        })
        res.write('retry: 10000\n')
        res.write("event: connecttime\n");
        res.write("data: " + (new Date()) + "\n\n");

        const interval = setInterval(function() {
            res.write("data: " + (new Date()) + "\n\n");
        }, 3000)
        req.connection.addListener("close", function () {
            clearInterval(interval);
        }, false);
    }
}).listen(9988, '127.0.0.1')

You can copy the above code to the local, node run to see the effect of Ha
github: https://github.com/superNos/SSE-Demo

Learning from Ruan Yifeng's Great God Articles
The original text of the Great God: http://www.ruanyifeng.com/blo...

Tags: Javascript Steam hot update Webpack github

Posted on Thu, 10 Oct 2019 03:24:39 -0700 by prashanth0626