uniapp封装websocket以及心跳检测、重连

本文介绍了如何在uni-app项目中封装WebSocket连接,包括构造函数、连接初始化、发送消息、心跳检测以及重连逻辑。同时展示了如何在不同场景中使用和管理WebSocket实例。
摘要由CSDN通过智能技术生成

websocket 封装

在所需文件夹下建立websocketUtils.js文件,封装代码如下:

class websocketUtils {
	constructor(openId, time) {
		this.url = `wss://****` //ws地址 拼接一下 此处用的是openId
		this.data = null
        this.isOpenSocket = false //避免重复连接
		this.timeout = time //隔多久执行检测 单位秒(s)
		this.heartbeatInterval = null //检测服务器端是否还存活
		this.reconnectTimeOut = null //重连之后隔多久才再次重连
		try {
			return this.connectSocketInit()
		} catch (e) {
			console.log('===========连接错误捕获catch====================',e);
			this.isOpenSocket = false
			this.reconnect();
		}
	}
	// 创建websocket连接
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
      header: {
        //头部可以添加所需字段如token
        'content-type': 'application/json'
      },
			success:()=>{
				console.log("============正准备建立websocket中================");
				// 返回实例
				return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("==============WebSocket连接正常=============");
			clearTimeout(this.reconnectTimeOut)
			clearInterval(this.heartbeatInterval)
			this.isOpenSocket = true;
			this.start();
			// 只有连接正常打开中 ,才能正常收到消息
			this.socketTask.onMessage((res) => {
				console.log(res.data,'===============接收===onMessage===============')
            //全局注册uniapp事件,在任何页面都能接受到
        uni.$emit('socketMessage', res)
			});
		})
		// 监听失败,再次打开 判断主动重连
		// uni.onSocketError((res) => {
		// 	console.log('==========WebSocket连接打开失败哦===============');
		 //	this.isOpenSocket = false;
		 //	this.reconnect();
		// });
		//  socket关闭了会执行 此处
		this.socketTask.onClose((e) => {
			console.log("========已经被关闭了====================",e)
			this.isOpenSocket = false;
            // 加了flag判断是否为手动(用户主动关闭)
			e && e.reason == 'user' ? '' : this.reconnect();
		})
	}
	//发送消息
	send(value){
		//  连接正常打开时 ,才能正常成功发送消息
		this.socketTask.send({
			data: value,
			async success() {
				console.log("===========消息发送成功===============");
			},
		});
	}
	//开启心跳检测
	start(){
    this.data={value:"发送心跳内容",method:"发送心跳方法名称"}
		this.heartbeatInterval = setInterval(()=>{
			console.log('======start====开启心跳检测====',this.data)
			this.send(JSON.stringify(this.data));
		},this.timeout * 1000)
	}
	//重新连接
	reconnect(){
		//停止发送心跳
		clearInterval(this.heartbeatInterval)
		//如果不是人为关闭的话,进行重连
		if(!this.isOpenSocket ){
			this.reconnectTimeOut = setTimeout(()=>{
				this.connectSocketInit();
			},3000)
		}
	}
  // 关闭 WebSocket 连接
  closeSocket(reason = '关闭') {
    const _this = this
    this.socketTask.close({
      reason,
      success() {
        _this.data = null
        _this.isOpenSocket = false
        _this.socketTask = null
        clearTimeout(_this.reconnectTimeOut)
        clearInterval(_this.heartbeatInterval)
        console.log('===============关闭 WebSocket 成功===================')
      },
      fail() {
        console.log('===================关闭 WebSocket 失败=====================')
      }
    })
  }
	//将获取的消息导出外部
	exportMessage(callback) {
		this.socketTask.onMessage((res) => {
      console.log(res,'===============exportMessage============')
			return callback(res)
		})
	}
}
 
 
module.exports = websocketUtils 

页面引入使用 

全局引入:

1.在main.js中引入,并全局注册

//引入websocket文件
import websocketUtils from '@/utils/websocketUtils.js'

//挂载并开启websocket
Vue.prototype.$socketUtils = new websocketUtils("*******",10)

 2.指定页面中使用

// 发送消息
let data={value:"发送的value"}
this.$socketUtils.send(JSON.stringify(data));

// 接收消息
this.$socketUtils.exportMessage(res=>{
	console.log(res);
})
 单页面使用引入:
<!--  页面  -->
<template>
  <view class='e-about-operation-wrap'>
  </view>
</template>

<script>
  import websocketUtils  from '@/utils/websocketUtils.js'
  const app = getApp()
  export default {
    name: 'ESign',
    components: {},
    data() {
      return { };
    },
    onLoad: function(option) {
    },
    onShow: function() {
      //在uniapp全局中定义了socketWBObj变量
      app.globalData.socketWBObj = new websocketUtils(this.user.loginInfo.openId,10)
      //监听获取消息
      uni.$on('socketMessage', this.wbSocketGetMsg)
      //方法获取收到的消息
      app.globalData.socketWBObj.exportMessage(res => {
		console.warn(res);
	  })
    },
    onHide: function() {
      
    },
    onUnload(e) {
     
    },
    created() {},
    mounted() {
    },
    methods: {
      wbSocketGetMsg(res){
        const _this = this
        console.log(res,'======wbSocketGetMsg==========')
        // 关闭连接
        if (app.globalData.socketWBObj) {
           app.globalData.socketWBObj.closeSocket('user')
        }
      }
    },
    watch: {},
    computed: {},
  }
</script>
<style lang='scss' scoped>
.e-about-operation-wrap{
  
}
</style>

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个示例代码,实现了Uniapp封装WebSocket的功能,包括重连和心跳功能,并可以在全局使用。 ```javascript // utils/websocket.js const HEARTBEAT_TIME = 30 * 1000 // 心跳时间间隔 class WebSocketUtil { constructor(url, options = {}) { this.url = url this.options = options this.socket = null this.isReconnecting = false // 是否正在重连 this.heartbeatInterval = null // 心跳定时器 } connect() { return new Promise((resolve, reject) => { this.socket = uni.connectSocket({ url: this.url, ...this.options, success: () => { this.initEvent() resolve() }, fail: reject, }) }) } initEvent() { this.socket.onOpen(() => { console.log('WebSocket连接已打开') this.startHeartbeat() // 开始心跳 }) this.socket.onClose((e) => { console.log('WebSocket连接已关闭', e) this.stopHeartbeat() // 停止心跳 if (!this.isReconnecting) { this.isReconnecting = true this.reconnect() // 重连 } }) this.socket.onError((e) => { console.log('WebSocket连接发生错误', e) this.stopHeartbeat() // 停止心跳 if (!this.isReconnecting) { this.isReconnecting = true this.reconnect() // 重连 } }) this.socket.onMessage((res) => { console.log('WebSocket收到消息', res) }) } reconnect() { setTimeout(() => { console.log('WebSocket正在重连...') this.connect().then(() => { console.log('WebSocket重连成功') this.isReconnecting = false }).catch(() => { console.log('WebSocket重连失败') this.reconnect() }) }, 3000) } startHeartbeat() { this.heartbeatInterval = setInterval(() => { if (this.socket.readyState === 1) { console.log('WebSocket发送心跳') this.socket.send({ type: 'heartbeat' }) } }, HEARTBEAT_TIME) } stopHeartbeat() { clearInterval(this.heartbeatInterval) } } export default { install(Vue) { const websocket = new WebSocketUtil('wss://example.com') Vue.prototype.$websocket = websocket websocket.connect() }, } ``` 使用时,在main.js中引入并注册即可: ```javascript // main.js import Vue from 'vue' import App from './App.vue' import websocket from './utils/websocket' Vue.config.productionTip = false Vue.use(websocket) new Vue({ render: h => h(App), }).$mount('#app') ``` 在组件中,可以通过`this.$websocket`来获取WebSocket实例,然后进行发送消息等操作: ```javascript // HelloWorld.vue export default { mounted() { this.$websocket.socket.send({ type: 'hello' }) } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值