短轮询:设置一个定时器,定时询问服务器是否有信息,每次建立连接传输数据之后,连接会关闭。
var polling = function (url, type, data) {
var xhr = new XMLHttpRequest(),
type = type || "GET",
data = data | null;
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
reveive(xhr.responseText);
xhr.onreadystatechange = null;
}
};
xhr.open(type, url, true);
xhr.send(type == "GET" ? null : data);
};
var timer = setInterval(function () {
polling;
}, 1000);
长轮询:在xhr对象关闭连接的时候马上又给他接上
// 长轮询
var longPoll = function (type, url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
receive(xhr.responseText);
xhr.onreadystatechange = null;
longPoll(type, url);
}
};
xhr.open(type, url, true);
xhr.send();
};
WebSocket是全双工、双向、单套接字连接。WebSocket是一个底层网络协议,可以在它的基础上构建其他标准协议。
一旦建立起WebSocket请求,不需要客户端发起,客户端也能及时接收到来自服务端的数据。
var ws = new WebSocket("ws:www.example.com:8888");
ws.onopen = function (evt) {};
ws.onmessage = function (evt) {
deal(evt.data);
};
ws.onclose = function (evt) {};
ws.send(data)
// ws.close()
原文:https://www.cnblogs.com/xiaoxu-xmy/p/13716567.html