websocket的连接及使用

创建一个websocket.js文件

class websocketUtil {

constructor(url, time) {
this.is_open_socket = false //避免重复连接
this.url = url //地址
this.data = null
this.id = uni.getStorageSync('uid')
//心跳检测
this.timeout = time //多少秒执行检测
this.heartbeatInterval = null //检测服务器端是否还活着
this.reconnectTimeOut = null //重连之后多久再次重连
this.sendId = ""
try {
return this.connectSocketInit()
} catch (e) {
this.is_open_socket = false
this.reconnect();
}
}
// 进入这个页面的时候创建websocket连接【整个页面随时使用】
connectSocketInit() {
this.socketTask = uni.connectSocket({
url: this.url,
id: this.id,
success: (res) => {
console.log("正准备建立websocket中...", res, this.id, this.url);
// 返回实例
return this.socketTask
},
});
this.socketTask.onOpen((res) => {
console.log("WebSocket连接正常!");
clearTimeout(this.reconnectTimeOut)
clearTimeout(this.heartbeatInterval)
this.is_open_socket = true;
this.start(this.sendId);
// 注:只有连接正常打开中 ,才能正常收到消息
this.socketTask.onMessage((res) => {
let json = JSON.parse(res.data)
console.log(json, '后端信息');
uni.$emit("onMessage", json)
});
})
// 监听连接失败,这里代码我注释掉的原因是因为如果服务器关闭后,和下面的onclose方法一起发起重连操作,这样会导致重复连接
// uni.onSocketError((res) => {
// console.log('WebSocket连接打开失败,请检查!');
// this.is_open_socket = false;
// this.reconnect();
// });
// 这里仅是事件监听【如果socket关闭了会执行】
this.socketTask.onClose(() => {
this.is_open_socket = false;
this.reconnect();
})
}
//发送消息
send(value) {
// 注:只有连接正常打开中 ,才能正常成功发送消息
this.socketTask.send({
data: value,
async success() {},
});
}
//开启心跳检测
start(sendId) {
this.heartbeatInterval = setInterval(() => {
this.sendId = sendId
this.data = {
userId: this.id,
msgType: 1,
}
this.send(JSON.stringify(this.data));
}, this.timeout)
}
//重新连接
reconnect() {
//如果不是人为关闭的话,进行重连
if (!this.is_open_socket) {
this.reconnectTimeOut = setTimeout(() => {
this.connectSocketInit();
//停止发送心跳
clearInterval(this.heartbeatInterval)
}, 3000)
}
}
}
module.exports = websocketUtil

创建好以后需要在main.js文件中引入改文件,并注册为全局的量,、

//引入websocket文件
import wsRequest from 'websocket.js'

// let websocket = new wsRequest(`ws://地址`, 10000)
//挂载到全局
Vue.prototype.$socket = websocket

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值