背景
方法
- WebSocket
Comet
轮询的方式是比较传统的方式,它是在客户端设置一个定时器,指定一定时间后执行每个操作,或者递归ajax请求,伪代码如下:
1、定时器(也称轮询)123456789101112131415161718192021222324252627282930313233343536373839$(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 事件的特性.
|
- sharedWorker
- BoardcastChannel
总结
资源
跨浏览器通信库