浏览器跨进程通信方法初探

背景

方法

  • WebSocket
  • Comet
    轮询的方式是比较传统的方式,它是在客户端设置一个定时器,指定一定时间后执行每个操作,或者递归ajax请求,伪代码如下:
    1、定时器(也称轮询)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    $(function () {
    window.setInterval(function () {
    $.get("/api/getmessage",
    { "timed": new Date().getTime() },
    function (data) {
    $("#root").append("[data: " + data + " ]<br/>");
    });
    }, 3000);
    });
    ```
    这个方式的优点是后端写起来比较容易,不用考虑过多的因素,但是缺点也很明显,请求中大部分是无用的,浪费带宽和服务器资源。
    2、递归ajax(也称长轮询)
    ``` js
    $(function () {
    (function longPolling() {
    $.ajax({
    url: "/api/getmessage",
    data: { "timed": new Date().getTime() },
    dataType: "text",
    timeout: 5000,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
    $("#state").append("[state: " + textStatus + ", error: " + errorThrown + " ]<br/>");
    if (textStatus == "timeout") { // 请求超时
    longPolling(); // 递归调用
    // 其他错误,如网络错误等
    } else {
    longPolling();
    }
    },
    success: function (data, textStatus) {
    $("#state").append("[state: " + textStatus + ", data: { " + data + "} ]<br/>");
    if (textStatus == "success") { // 请求成功
    longPolling();
    }
    }
    });
    });
    })();

    这种方式的优点是始终和服务器保持一个连接,如果当前连接请求成功更新完数据以后,马上又会建立一个新的连接,如果连接超时或者请求错误,同样会继续创建一个新的连接,节省了服务器和网络资源,提高了程序的性能,缺点就是服务器要维护一个长连接增加开销。

  • LocalStorage
    主要是利用 Web Storage API 中的 localStorage 或者 sessionStorage 的发生变化时触发 storage 事件的特性.

1
2
  • sharedWorker
  • BoardcastChannel

总结

资源

跨浏览器通信库