You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zhishifufei_php/public/kefu-assets/libs/socket.js

102 lines
2.4 KiB

10 months ago
define(["vue"], (Vue) => {
const vm = new Vue;
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
const host = location.host;
const wsKefuSocketUrl = `${protocol}//${host}/wss?channel=kefu`;
class wsSocket {
constructor(opt) {
this.ws = null;
this.opt = opt || {};
this.init();
}
onOpen() {
this.opt.open && this.opt.open();
let that = this;
that.ping();
this.socketStatus = true;
}
init() {
this.ws = new WebSocket(wsKefuSocketUrl);
this.ws.onopen = this.onOpen.bind(this);
this.ws.onerror = this.onError.bind(this);
this.ws.onmessage = this.onMessage.bind(this);
this.ws.onclose = this.onClose.bind(this);
}
ping() {
var that = this;
this.timer = setInterval(function () {
that.send({ type: 'ping' });
}, 5000);
}
send(data) {
data.channel = "kefu";
return new Promise((resolve, reject) => {
try {
this.ws.send(JSON.stringify(data));
resolve({ status: true });
} catch (e) {
reject({ status: false })
}
});
}
onMessage(res) {
this.opt.message && this.opt.message(res);
}
onClose(e) {
console.log(e)
this.timer && clearInterval(this.timer);
this.opt.close && this.opt.close();
}
onError(e) {
console.log(e);
this.opt.error && this.opt.error(e);
}
$on(...args) {
vm.$on(...args);
}
clearEvent() {
vm.$off();
}
}
function createSocket(key) {
return new Promise((resolve, reject) => {
const ws = new wsSocket({
key,
open() {
resolve(ws);
},
error(e) {
reject(e)
},
message(res) {
const { type, data = {} } = JSON.parse(res.data);
vm.$emit(type, data);
},
close(e) {
vm.$emit('close', e);
}
})
});
}
return createSocket();
});