websocket在uniapp上的使用(心跳机制)

该代码段实现了一个WebSocket连接的管理,包括初始化连接、发送消息、心跳检测、断线重连和关闭连接的功能。在连接异常时会自动尝试重新连接,并有心跳机制确保连接状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

export default {
	url: xxx, // WebSocket的url
	data: null,
	isCreate: false,
	isConnect: false, // 是否已经连接
	isInitiative: false, // 是否主动断开
	timeoutNumber: 30, // 心跳检测间隔(单位秒)
	heartbeatTimer: null, // 心跳检测定时器
	reconnectTimer: null, // 断线重连定时器
	socketExamples: null, // websocket实例
	againTime: 3, // 重连等待时间(单位秒)
	

	// 初始化websocket连接
	createSocket(token) {
		const self = this
		try {
			self.socketExamples = uni.connectSocket({
				url: xxx,
				success: () => {
					self.isCreate = true
				},
				fail: () => {
					self.isCreate = false
				}
			})
		} catch (err) {
			console.log(err)
			console.log('websocket connection is abnormal, reconnecting...')
			self.reconnect(token)
		}
		self.initSocket()
	},

	// 创建websocket连接
	initSocket() {
		const self = this
		if (!self.isCreate) return
		self.socketExamples.onOpen(() => {
			console.log('WebSocket 连接成功')
			self.isConnect = true
			self.heartbeatTimer && clearInterval(self.heartbeatTimer)
			self.reconnectTimer && clearTimeout(self.reconnectTimer)
			// 打开心跳检测
			self.heartbeatCheck()
		})
		// 监听 WebSocket 接受到服务器的消息事件
		self.socketExamples.onMessage(({ data }) => {
			// console.log('收到消息')
			// console.log(res)
			uni.$emit('message', JSON.parse(data))
		})
		// 监听 WebSocket 连接关闭事件
		self.socketExamples.onClose(() => {
			console.log('WebSocket 关闭了')
			self.isConnect = false
			self.reconnect()
		})
		// 监听 WebSocket 错误事件
		self.socketExamples.onError((res) => {
			console.log('WebSocket 出错了')
			console.log(res)
			self.isInitiative = false
		})
	},

	// 发送消息
	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() {
		this.data = {
			type: 10
		}
		this.heartbeatTimer = setInterval(() => {
			this.sendMsg(this.data)
		}, this.timeoutNumber * 1000)
	},

	// 重新连接
	reconnect() {
		// 停止发送心跳
		this.reconnectTimer && clearTimeout(this.reconnectTimer)
		this.heartbeatTimer && clearInterval(this.heartbeatTimer)
		// 如果不是人为关闭的话,进行重连
		if (!this.isInitiative) {
			this.reconnectTimer = setTimeout(() => {
				this.createSocket()
			}, this.againTime * 1000)
		}
	},

	// 关闭 WebSocket 连接
	closeSocket(reason = '关闭') {
		const self = this
		this.socketExamples.close({
			reason,
			success() {
				self.data = null
				self.isCreate = false
				self.isConnect = false
				self.isInitiative = true
				self.socketExamples = null
				clearInterval(self.heartbeatTimer)
				clearTimeout(self.reconnectTimer)
				// console.log('关闭 WebSocket 成功')
			},
			fail() {
				console.log('关闭 WebSocket 失败')
			}
		})
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值