基础前端

Server-Sent Events服务器单向浏览器通信

2020-04-20  本文已影响0人  CondorHero

API 教程学习参考:Server-Sent Events 教程

接下来实战:

在 app 文件里面有文件:

├─app
│──── index.html
│──── app.js

index.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE</title>
    <style>

    </style>
</head>
<body>
    <button id="btn">开启SSE</button>
    <button id="btncClose">关闭SSE</button>
    <script>
        let source;
        btn.onclick = function(){
            if ('EventSource' in window) {
                const url = "/stream";
                source = new EventSource(url);
                // 表明连接的当前状态,只读
                console.log(source.readyState);
                source.onopen = function (event) {
                    console.log("open SSE");
                };
                // 默认接收事件
                source.onmessage = function (event) {
                    const data = event.data;
                    console.log("receive: " + data );
                };
                // 自定义事件
                source.connecttime = function (event) {
                    const data = event.data;
                    console.log("receive: " + data );
                };
                source.onerror = function (event) {
                    // handle error event
                    console.log("SSE error");
                };
            }
        };
        // 关闭SSE
        btncClose.onclick = function(){
            source.close();
            console.log("SSE 成功关闭");
        }
    </script>
</body>
</html>

NodeJs 的 app.js 文件:

const http = require("http");
const { readFile } = require("fs");

http.createServer(function(req, res) {
    // 请求URL
    console.log(req.url);

    const fileName = "." + req.url;

    // 加载页面
    if (fileName === "./index") {
        readFile("./index.html",function(err,data){
            const result = data.toString();
            res.end(result);
        });
    };
    // SSE
    if (fileName === "./stream") {
        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");
        res.write("data: " + (new Date()) + "\n\n");

        interval = setInterval(function() {
            res.write("data: " + (new Date()) + "\n\n");
        }, 1000);

        req.connection.addListener("close", function() {
            clearInterval(interval);
        }, false);
    }
}).listen(8888, "127.0.0.1");

现在只需要启动 app.js 文件,即在 CMD 窗口中 node app.js,在浏览器中直接访问http://127.0.0.1:8888/index 即可看到两个按钮:

两个按钮
执行效果:

SSE 完~

以前针对传统的 HTTP 请求优化是:

  1. 一种解决办法就是把外部资源合并在网页文件里面,减少 HTTP 请求。比如,把样式表的内容写在<style>标签之中,把图片改成 Base64 编码的 Data URL

  2. 另一种方法就是资源的预加载(preload)。网页预先告诉浏览器,立即下载某些资源。

这两种方法都有缺点。第一种方法虽然减少了 HTTP 请求,但是把不同类型的代码合并在一个文件里,违反了分工原则。第二种方法只是提前了下载时间,并没有减少 HTTP 请求。

现在 http2.0 服务器支持 服务器推送(Server Push)一些资源,不过需要手配。而且推送的资源不应该过多。

2020年4月20日23点19分

上一篇 下一篇

猜你喜欢

热点阅读