uniapp使用WebSocket uniapp使用WebSocket Uniapp整合WebSocket uniapp使用 websocket
前言
代码中的示例只在 H5、APP环境下成功运行,小程序环境下如果无效,需要使用预编译 - 条件性的编译,适配 小程序环境
// #ifdef MP-WEIXIN
// #endif
Uni-app 支持多种预编译指令,包括但不限于:
#ifdef H5
:针对 Web H5页面。#ifdef APP-PLUS
:针对原生应用(Android 和 iOS)。#ifdef MP-WEIXIN
:针对微信小程序。#ifdef MP-ALIPAY
:针对支付宝小程序。#ifdef MP-Baidu
:针对百度小程序。#ifdef MP-Toutiao
:针对字节跳动小程序。#ifdef MP-QQ
:针对 QQ 小程序。#ifdef MP-Kuaishou
:针对快手小程序。#ifdef MP-JD
:针对京东小程序。
1、Socket.js
// config.js 文件位于 uniapp根目录全局文件,如果没有,则固定将socket地址手动写死
import config from '@/config'
const socketUrl = config.baseSocketUrl
// 重试最大次数, 避免出现网络错误停留在页面 出现无限socket重连导致 浏览器卡死
const retryMaxTimes = 10
let retryTimes = 1
class WebSocketClass {
constructor() {
this.lockReconnect = false; // 是否开始重连
this.wsUrl = ""; // ws 地址
// this.globalCallback = this.globalCallback(); // 回调方法
this.userClose = false; // 是否主动关闭
this.createWebSocket(socketUrl);
}
createWebSocket(url) {
// #ifdef H5
if (typeof(WebSocket) === 'undefined') {
this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
return false
}
// #endif
// #ifdef APP-PLUS
if (typeof(uni.connectSocket) === 'undefined') {
this.writeToScreen("您的浏览器不支持WebSocket,无法获取数据");
return false
}
// #endif
this.wsUrl = url;
try {
// 创建一个this.ws对象【发送、接收、关闭socket都由这个对象操作】
// #ifdef H5
this.ws = new WebSocket(this.wsUrl);
// 更改消息数据格式为 arraybuffer
this.ws.binaryType = 'arraybuffer';
this.initEventHandle();
// #endif
// #ifdef APP-PLUS
this.ws = uni.connectSocket({
url: this.wsUrl,
success(data) {
console.log("websocket连接成功");
// 更改消息数据格式为 arraybuffer
this.ws.binaryType = 'arraybuffer';
this.initEventHandle();
},
});
// #endif
} catch (e) {
this.reconnect(url);
}
}
// 初始化
initEventHandle() {
var _this = this
_this.ws.binaryType = 'arraybuffer';
console.info(_this)
/**
* 监听WebSocket连接打开成功
*/
// #ifdef H5
_this.ws.onopen = (event) => {
console.log("WebSocket连接打开");
};
// #endif
// #ifdef APP-PLUS
_this.ws.onOpen(res => {
console.log('WebSocket连接打开');
});
// #endif
/**
* 连接关闭后的回调函数
*/
// #ifdef H5
_this.ws.onclose = (event) => {
if (!_this.userClose) {
_this.reconnect(_this.wsUrl); //重连
}
};
// #endif
// #ifdef APP-PLUS
_this.ws.onClose(() => {
if (!_this.userClose) {
_this.reconnect(_this.wsUrl); //重连
}
});
// #endif
/**
* 报错时的回调函数
*/
// #ifdef H5
_this.ws.onerror = (event) => {
if (!_this.userClose) {
_this.reconnect(_this.wsUrl); //重连
}
};
// #endif
// #ifdef APP-PLUS
_this.ws.onError(() => {
if (!_this.userClose) {
_this.reconnect(_this.wsUrl); //重连
}
});
// #endif
/**
* 收到服务器数据后的回调函数
*/
// #ifdef H5
_this.ws.onmessage = (event) => {
if (_this.isJSON(event.data)) {
const jsonobject = JSON.parse(event.data)
_this.globalCallback(jsonobject)
} else {
_this.globalCallback(event.data)
}
};
// #endif
// #ifdef APP-PLUS
_this.ws.onMessage(event => {
if (_this.isJSON(event.data)) {
const jsonobject = JSON.parse(event.data)
_this.globalCallback(jsonobject)
} else {
_this.globalCallback(event.data)
}
});
// #endif
}
// 关闭ws连接回调
reconnect(url) {
if (this.lockReconnect) return;
this.ws.close();
this.lockReconnect = true; // 关闭重连,没连接上会一直重连,设置延迟避免请求过多
if (retryTimes < retryMaxTimes) {
retryTimes = retryTimes + 1
console.info('WebSocket当前重试次数', retryTimes)
setTimeout(() => {
this.createWebSocket(url);
this.lockReconnect = false;
}, 1000);
}else{
console.info('WebSocket当前已经重试最大次数,依旧无法连接,不在重试,请检查网络是否正常')
}
}
// 发送信息方法
webSocketSendMsg(msg) {
this.ws.send(JSON.stringify(msg));
}
// 获取ws返回的数据方法
getWebSocketMsg(callback) {
this.globalCallback = callback
}
globalCallback(data) {
return new Promise((resolve, reject) => {
resolve(data); // 成功时调用resolve
});
}
// 关闭ws方法
closeSocket() {
if (this.ws) {
this.userClose = true;
this.ws.close({
success(res) {
console.log("关闭成功", res)
},
fail(err) {
console.log("关闭失败", err)
}
});
}
}
writeToScreen(massage) {
console.log(massage);
}
isJSON(str) {
if (typeof str == 'string') {
try {
var obj = JSON.parse(str);
if (typeof obj == 'object' && obj) {
return true;
} else {
return false;
}
} catch (e) {
// console.log('error:'+str+'!!!'+e);
return false;
}
}
// console.log('It is not a string!')
}
}
export default WebSocketClass;
2、main.js引入
import WS from "@/utils/socket.js"
const ws = new WS()
Vue.prototype.$ws = ws
const app = new Vue({
...App
})
3、组件中调用
export default {
data() {
return {
}
},
mounted() {
const _t = this
// 发送消息
_t.$ws.webSocketSendMsg({'msg': 'hello'})
// 监听服务端发送的消息
_t.$ws.getWebSocketMsg((res) => {
console.info('接收消息', res)
})
}
}