uniapp 建立 websocket 连接
uniapp websocket
open in new window
封装 websocket
class webSocketClass {
constructor(userId, time = 60) {
this.url = `ws://h5demo.funversy.com/message/websocket/socket.io/?transport=websocket&userId=${userId}&type=message`;
this.data = null;
this.isCreate = false;
this.isConnect = false;
this.isInitiative = false;
this.timeoutNumber = time;
this.heartbeatTimer = null;
this.reconnectTimer = null;
this.socketExamples = null;
this.againTime = 3;
}
initSocket() {
const _this = this;
this.socketExamples = uni.connectSocket({
url: _this.url,
header: {
"content-type": "application/json",
},
success: (res) => {
_this.isCreate = true;
console.log(res);
},
fail: (rej) => {
_this.isCreate = false;
console.error(rej);
},
});
this.createSocket();
}
createSocket() {
if (this.isCreate) {
console.log("WebSocket 开始初始化");
try {
this.socketExamples.onOpen(() => {
console.log("WebSocket 连接成功");
this.isConnect = true;
clearInterval(this.heartbeatTimer);
clearTimeout(this.reconnectTimer);
this.heartbeatCheck();
});
this.socketExamples.onMessage((res) => {
console.log("接收webSocket消息", res);
let msg = res.data;
if (msg.includes('42["/topic/message"')) {
uni.$emit("socket-message", JSON.parse(msg.split("42")[1])[1]);
}
});
this.socketExamples.onClose(() => {
console.log("WebSocket 关闭了");
this.isConnect = false;
this.reconnect();
});
this.socketExamples.onError((res) => {
console.log("WebSocket 出错了");
console.log(res);
this.isInitiative = false;
});
} catch (error) {
console.warn(error);
}
} else {
console.warn("WebSocket 初始化失败!");
}
}
sendMsg(value) {
const param = JSON.stringify(value);
return new Promise((resolve, reject) => {
this.socketExamples.send({
data: param,
success() {
console.log("消息发送成功");
resolve(true);
},
fail(error) {
console.log("消息发送失败");
reject(error);
},
});
});
}
heartbeatCheck() {
console.log("开启心跳");
this.data = { state: 1, method: "heartbeat" };
this.heartbeatTimer = setInterval(() => {
this.sendMsg(this.data);
}, this.timeoutNumber * 1000);
}
reconnect() {
clearTimeout(this.reconnectTimer);
clearInterval(this.heartbeatTimer);
if (!this.isInitiative) {
this.reconnectTimer = setTimeout(() => {
this.initSocket();
}, this.againTime * 1000);
}
}
closeSocket(reason = "关闭") {
const _this = this;
this.socketExamples.close({
reason,
success() {
_this.data = null;
_this.isCreate = false;
_this.isConnect = false;
_this.isInitiative = true;
_this.socketExamples = null;
clearInterval(_this.heartbeatTimer);
clearTimeout(_this.reconnectTimer);
console.log("关闭 WebSocket 成功");
},
fail() {
console.log("关闭 WebSocket 失败");
},
});
}
}
export default webSocketClass;
function initSocket(userId) {
if (userId) {
if (getApp().globalData.socketObj) {
if (!getApp().globalData.socketObj.isConnect) {
getApp().globalData.socketObj.initSocket();
}
} else {
const data = getAppInfo().globalData.user;
getApp().globalData.socketObj = new WebSocketClass(userId, 60);
getApp().globalData.socketObj.initSocket();
}
}
}
function closeSocket() {
if (
getApp().globalData.socketObj &&
getApp().globalData.socketObj.isConnect
) {
getApp().globalData.socketObj.closeSocket();
}
}