function createWorker() {
const script_content = `class CircularQueue {
constructor(size = 1) {
this.size = size;
this.data = new Array(size).fill(null);
this.front = this.rear = -1;
}
put(data) {
if ((this.rear + this.front + 1) >= this.size || this.front > this.rear) {
// condition if queue is full
this.data[this.rear] = data;
this.front = (this.front + 1) % this.size;
this.rear = (this.rear + 1) % this.size;
} else if (this.front === this.rear) {
// condition for empty queue
this.front = 0;
this.data[this.front] = data;
this.rear = (this.front + 1) % this.size;
} else {
// next position of rear
this.data[this.rear] = data;
this.rear = (this.rear + 1) % this.size;
}
}
empty() {
return this.front === -1;
}
get() {
if (this.empty()) {
return null;
}
const rtn = this.data[this.front];
this.data[this.front] = null;
if (this.front !== this.rear) {
this.front = (this.front + 1) % this.size;
} else {
this.front = this.rear = -1;
}
return rtn;
}
display() {
console.log(this.data, this.front, this.rear);
}
};
let buffer = new CircularQueue(500);
setInterval(() => {
let data = buffer.get();
if(data != null){
postMessage(['onMsg', data]);
}
}, 500);
let url = '';
self.addEventListener('message', function(e) {
let flag = e.data[0]
let data = e.data[1]
if(flag === 'create'){
url = data;
initWebSocket();
}
});
function initWebSocket(){
let ws = new WebSocket(url);
ws.addEventListener('open', (event) => {
console.log('已连接: ' + url);
postMessage(['onOpen', '']);
});
ws.addEventListener('message', (event) => {
buffer.put(event.data);
// console.log('111');
});
ws.addEventListener('close', (event) => {
console.log('已断开: ' + url);
postMessage(['onClose', '']);
reconnect();
});
ws.addEventListener('error', (event) => {
console.log('发送错误: ' + url);
});
}
let lockReconnect = false;
function reconnect(){
if (lockReconnect) return;
lockReconnect = true;
setTimeout(function () {
console.log('准备重连: ' + url);
initWebSocket();
lockReconnect = false;
}, 5000);
}
`;
const blob2 = new Blob([script_content], { type: "text/javascript" });
const myWorker = new Worker(URL.createObjectURL(blob2), { type: 'module' });
return myWorker;
}
export function subMoving(ws, onOpenFun, onMsgFun, onCloseFun) {
var url = window._CONFIG['domianURL'].replace("https://", "wss://").replace("http://", "ws://") + "/threed_model/ws/warehouse/moving";
let myWorker = createWorker();
myWorker.addEventListener('message', function (event) {
let flag = event.data[0];
let data =event.data[1];
if(flag === 'onOpen'){
if(onOpenFun != null){
onOpenFun();
}
}else if(flag === 'onMsg'){
if(onMsgFun != null){
onMsgFun(data);
}
}else if(flag === 'onClose'){
if(onCloseFun != null){
onCloseFun();
}
}else{
console.error('unknow flag');
}
});
myWorker.postMessage(['create', url]);
}
export function unSubMoving(ws) {
ws.close();
ws = null;
}