zoukankan      html  css  js  c++  java
  • HTML 5 ShareWorker

    ShareWorker和Worker区别

    worker:专属线程,只针对当前运行环境(HTML 5 Web Workers

    sharedWorker:共享线程,同源策略下,多个运行环境共用同一个线程,包括数据。

    方法

    • start:开启连接
    • connect:连接
    • postMessage:发送数据
    • onmessage:接收数据

    页面通信举例

    页面

    <body>
        <input type="text" id="input">
        <button id="submit">提交</button>
        <p id="news"></p>
    </body>
    <script>
        let work = new SharedWorker('work.js');
        let port = work.port;
        //开启
        port.start();
        //通知所有人
        port.postMessage({ type: "start" });
        //点击触发事件
        submit.onclick = function (e) {
            port.postMessage({
                type: "msg",
                value: input.value
            });
            input.value = "";
        }
        //接收数据
        port.onmessage = function (e) {
            console.log(e.data)
            if (Array.isArray(e.data)) {
                let html = "";
                e.data.forEach(msg => {
                    html += `<p>${msg}</p>`;
                });
                news.innerHTML = html;
            } else {
                news.innerHTML = e.data;
            }
        }
    </script>
    

    work.js

    let connectList = [], msgList = [];
    self.onconnect = function (w) {
        // 开启
        let port = w.ports[0];
        port.start();
        // 监听
        port.onmessage = function (e) {
            let worker = e.currentTarget, data = e.data;
            // 加入到列表
            if (connectList.indexOf(worker) === -1) {
                connectList.push(worker);
            }
            //新用户进入 
            if (data.type === "start") {
                connectList.forEach(item => {
                    if (item === worker)
                        item.postMessage("你已进入");
                    else
                        item.postMessage("新用户进入");
                })
            }
            //新消息
            if (data.type === "msg") {
                msgList.push(data.value);
                connectList.forEach(item => {
                    item.postMessage(msgList);
                })
            }
        }
    }
    
    
  • 相关阅读:
    Linux常用命令学习2---(文件搜索命令locate find、命令搜索命令whereis which、字符串搜索命令grep、帮助命令man)
    LeetCode Perfect Squares
    华为笔试 数字转中文拼音
    二位数组 顺时针打印矩阵
    LeetCode Interleaving String
    LeetCode Coins in a Line
    LeetCode Backpack
    LeetCode Unique Paths
    LeetCode Minimum Path Sum
    腾讯模拟笔试题
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/13234516.html
Copyright © 2011-2022 走看看