syl*_*ain 5 javascript ajax websocket socket.io
我正在寻找一个javascript客户端lib来处理像这样的ajax或websocket请求队列:
理想情况下:
我找不到这样的东西.我应该自己使用localstorage构建一个,例如window.navigator.onLine和socket.io还是已经有一些用于此目的的lib?
谢谢.
这个问题可能会结束,因为在 StackOverflow 上通常不欢迎要求图书馆。然而,这是一个有趣的小挑战。(我花了大约 15 分钟才完成。)
这实际上不是一个非常大的任务,只有 50 行左右。这可能就是您找不到这样做的小型图书馆的原因。
function Sender() {
var requests = [],
state = 0; // 0 = closed, 1 = open
ws = new WebSocket();
ws.onopen = function() {
state = 1;
if (requests.length) {
send();
}
};
ws.onerror = function() {
if (ws.readyState !== 1) { // 1 is "OPEN"
close();
}
};
// Let's fill in the requests array if necessary
// IIFE because I don't want to pollute the scope with `req`
(function() {
var req = JSON.parse(localStorage.get('queue'));
if (req.length) {
requests = requests.concat(req);
}
}());
return {
send: function(msg) {
if (state === 0) {
requests.push(msg);
}
else {
send();
}
},
close: function() {
state = 0;
localStorage.set('queue', JSON.stringify(requests));
}
};
function send() {
var done = false;
while (!done) {
if (state === 1) {
ws.send(requests.pop());
if (!requests.length) {
done = true;
}
}
else {
done = true;
}
}
}
}
// Usage example
var sender = Sender();
sender.send('message');
// let's say your "disconnect" button is in a variable
disconnect.addEventListener('click', function() {
sender.close();
}, false);
Run Code Online (Sandbox Code Playgroud)
除了正常的请求,服务器不必处理任何事情。如果需要,您可以在发送的消息中添加时间戳,这样可以很容易地(2 行左右)跟踪时间。
| 归档时间: |
|
| 查看次数: |
1261 次 |
| 最近记录: |