49 lines
1.6 KiB
JavaScript
49 lines
1.6 KiB
JavaScript
const core = function (){
|
|
function SocketWorker(url,token){
|
|
var _ctx = this.$ctx = { state:null };
|
|
this.socket = new WebSocket(url);
|
|
|
|
this.socket.onopen = function () {
|
|
postMessage({"name":"onopen","payload":null},[]);
|
|
}
|
|
this.socket.onclose = function (args) {
|
|
let { code,reason,type,target } = args;
|
|
let { url } = target;
|
|
postMessage({"name":"onclose","payload":{code,reason,type,url}});
|
|
console.log("closed",_ctx.state );
|
|
}
|
|
this.socket.onerror = function () {
|
|
postMessage({"name":"onerror","payload":null});
|
|
}
|
|
this.socket.onmessage = function (e) {
|
|
if(e.data.size < 32) return;
|
|
e.data.arrayBuffer().then(function(buffer){
|
|
postMessage({"name":"onmessage","payload":buffer},[buffer]);
|
|
});
|
|
}
|
|
}
|
|
SocketWorker.prototype.state = function(state){
|
|
this.$ctx.state = state;
|
|
}
|
|
SocketWorker.prototype.close = function(){
|
|
if(this.socket)this.socket.close();
|
|
}
|
|
SocketWorker.prototype.postMessage = function(){
|
|
this.socket.postMessage(...arguments);
|
|
}
|
|
let _websocket;
|
|
addEventListener('message',function(e){
|
|
let { name , payload } = e.data;
|
|
switch(name){
|
|
case "create":
|
|
let {url,token,state} = payload;
|
|
_websocket = new SocketWorker(url,token);
|
|
break;
|
|
case "close":
|
|
_websocket?.close();
|
|
break;
|
|
default:
|
|
_websocket?.postMessage(e.data)
|
|
}
|
|
});
|
|
}; |