提交代码
This commit is contained in:
75
src/utils/webSocket.js
Normal file
75
src/utils/webSocket.js
Normal file
@ -0,0 +1,75 @@
|
||||
const url = "ws://80.155.0.82:8006/mosty-api/mosty-websocket/socket/"; //线上
|
||||
import {
|
||||
getItem
|
||||
} from "@/utils/storage";
|
||||
import {
|
||||
getUserInfoToId
|
||||
} from "@/api/user-manage";
|
||||
class WebSoketClass {
|
||||
constructor(props) {}
|
||||
ws = null;
|
||||
static getInstance() {
|
||||
if (!this.ws) this.ws = new WebSoketClass();
|
||||
return this.ws;
|
||||
}
|
||||
//关闭连接
|
||||
static close() {
|
||||
this.ws.ws.close();
|
||||
}
|
||||
// 创建连接
|
||||
connect(fun) {
|
||||
let uuid = this.getUUid()
|
||||
let id = getItem("USERID");
|
||||
getUserInfoToId(id).then((res) => {
|
||||
let sfzh = res.idEntityCard
|
||||
this.ws = new WebSocket(url + sfzh + '/' + uuid);
|
||||
this.ws.onopen = (e) => { fun(true);};
|
||||
});
|
||||
}
|
||||
// 心跳机制
|
||||
heartCheck() {
|
||||
const _that = this;
|
||||
this.state = setInterval(() => {
|
||||
if (this.ws.readyState === 1) {
|
||||
this.ws.send("/heart");
|
||||
} else {
|
||||
this.closeHandle(); //重新连接
|
||||
}
|
||||
}, 6e3);
|
||||
}
|
||||
|
||||
// 获取uuid
|
||||
getUUid() {
|
||||
var s = [];
|
||||
var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyz";
|
||||
for (var i = 0; i < 32; i++) {
|
||||
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
|
||||
}
|
||||
s[14] = "4";
|
||||
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
|
||||
s[8] = s[13] = s[18] = s[23];
|
||||
let uuid = s.join("");
|
||||
return uuid
|
||||
}
|
||||
|
||||
closeHandle() {
|
||||
if (this.state) {
|
||||
clearInterval(this.state);
|
||||
this.connect();
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
// 接收发送消息
|
||||
getMessage() {
|
||||
this.ws.onmessage = (e) => {
|
||||
if (e.data) {
|
||||
let newsDate = JSON.parse(e.data);
|
||||
this.newVal = newsDate;
|
||||
//接收的数据
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
export default WebSoketClass;
|
Reference in New Issue
Block a user