前端js 队列(socket认证机制)

// 基于数组封装队列类
function Queue() {
// 属性
this.items = []
// 方法
// 1.enqueue():将元素加入到队列中
Queue.prototype.enqueue = element => {
this.items.push(element)
}

// 2.dequeue():从队列中删除前端元素
Queue.prototype.dequeue = () => {
return this.items.shift()
}

// 3.front():查看前端的元素
Queue.prototype.front = () => {
return this.items[0]
}

// 4.isEmpty:查看队列是否为空
Queue.prototype.isEmpty = () => {
return this.items.length === 0;
}

// 5.size():查看队列中元素的个数
Queue.prototype.size = () => {
return this.items.length
}

// 6.toString():将队列中元素以字符串形式输出
Queue.prototype.toString = () => {
let resultString = ''
for (let i of this.items) {
resultString += i + ' '
}
return resultString
}
}

 

// 发送消息列表 接收到消息回发后移除该消息 否则超过3秒自动重发
window.msgQueue = new Queue();

setInterval(() => {
let now = parseInt(new Date().getTime() / 1000 + "");
if (window.msgQueue.size() > 0) {
let msg = window.msgQueue.front();
if (now - msg.unix > 3) {
if (window.ws && window.ws.readyState === 1) {
//发送消息
msg.unix = now;
let str = JSON.stringify(msg);
let msgEnc = encStr(str);
window.ws.send(msgEnc)
if (show_log) {
console.info("↑ WS消息重发", msg);
}
}
}
}
}, 300)

// 接收消息时队列中移除
if (msgObj.c === 666) {
if (window.msgQueue.size() > 0) {
let msgitem = window.msgQueue.front();
if (msgitem.mid === msgObj.mid) {
logger.info("队列移除消息", msgitem)
window.msgQueue.dequeue();
}
logger.info("队列剩余消息条数", window.msgQueue.size())
}
}

posted @ 2023-01-09 10:33  波仔、  阅读(92)  评论(0编辑  收藏  举报