uniapp小程序webSocket封装使用
1,前言
最近在做IOT
的项目,里面有个小程序要用到webSocket
,借这个机会,封装了一个uniapp小程序
适用的Socket
类,具体实现如下。
2,代码实现
class webSocketClass {
constructor(url, interval) {
this.url = url
this.data = null
this.isCreate = false // WebSocket 是否创建成功
this.isConnect = false // 是否已经连接
this.isInitiative = false // 是否主动断开
this.heartbeatInterval = interval // 心跳检测间隔
this.heartbeatTimer = null // 心跳检测定时器
this.reconnectTimer = null // 断线重连定时器
this.socketExamples = null // websocket实例
this.againTime = 3 // 重连等待时间(单位秒)
}
// 初始化websocket连接
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) => {
console.error(rej)
_this.isCreate = false
}
})
this.createSocket()
}
// 创建websocket连接
createSocket() {
console.log('WebSocket 开始初始化')
if (this.isCreate) {
// 监听 WebSocket 连接打开事件
try {
this.socketExamples.onOpen(() => {
console.log('WebSocket 连接成功')
this.isConnect = true
clearInterval(this.heartbeatTimer)
clearTimeout(this.reconnectTimer)
// 打开心跳检测
this.heartbeatCheck()
})
// 监听 WebSocket 接受到服务器的消息事件
this.socketExamples.onMessage((res) => {
console.log('收到消息')
uni.$emit('message', res)
})
// 监听 WebSocket 连接关闭事件
this.socketExamples.onClose(() => {
console.log('WebSocket 关闭了')
this.isConnect = false
this.reconnect()
})
// 监听 WebSocket 错误事件
this.socketExamples.onError((res) => {
console.log('WebSocket 出错了')
console.log(res)
this.reconnect()
})
} 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.heartbeatInterval * 1000)
}
// 重新连接
reconnect() {
// 停止发送心跳
clearInterval(this.heartbeatTimer)
clearTimeout(this.reconnectTimer)
// 如果不是人为关闭的话,进行重连
if (!this.isInitiative) {
this.reconnectTimer = setTimeout(() => {
this.initSocket()
}, this.againTime * 1000)
}
}
// 关闭 WebSocket 连接
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
3,使用
直接实例化封装的socket
类,调用初始化方法就行了,当收到消息的时候,会触发$emit
事件,只需要使用$on
监听message
事件就行。
3.1,初始化
import WebSocketClass from '../../utils/webSocket'
const app = getApp()
onLoad() {
app.globalData.socketObj = new WebSocketClass('wss://www.baidu.com', 90)
app.globalData.socketObj.initSocket()
}
3.2,发送消息
methods: {
sendMessage() {
const param = { value: '我是一个消息' }
app.globalData.socketObj.sendMsg(param)
}
}
3.3,接收消息
// 开启监听
onLoad() {
uni.$on('message', this.getMessage)
},
// 页面卸载时取消监听
onUnload() {
uni.$off('message', this.getMessage)
},
methods: {
// 接收到消息的回调
getMessage(msg) {
console.log(msg)
}
}
如果看了觉得有帮助的,我是@鹏多多,欢迎 点赞 关注 评论;END
PS:在本页按F12,在console中输入document.querySelectorAll('.diggit')[0].click(),有惊喜哦
公众号
往期文章
- 超详细的Cookie增删改查
- 助你上手Vue3全家桶之Vue-Router4教程
- 助你上手Vue3全家桶之Vue3教程
- 助你上手Vue3全家桶之VueX4教程
- 使用nvm管理node.js版本以及更换npm淘宝镜像源
- 超详细!Vue-Router手把手教程
- vue中利用.env文件存储全局环境变量,以及配置vue启动和打包命令
- 微信小程序实现搜索关键词高亮
- 超详细!Vue的九种通信方式
- 超详细!Vuex手把手教程
个人主页
uniapp小程序webSocket封装使用的更多相关文章
- 微信小程序websocket
微信小程序websocket 微信小程序带有websocket可以提供使用,但是官方文档写的东西很少,而且小程序后台能力弱这一点也是十分的坑爹,这就导致了socket长连接一切后台就会出现断开的情况, ...
- 微信小程序:封装全局的promise异步调用方法
微信小程序:封装全局的promise异步调用方法 一:封装 function POST(url, params) { let promise = new Promise(function (resol ...
- 微信小程序 WebSocket 使用非 443 端口连接
前言 微信小程序支持使用 WebSocket 连接到服务器,准确地说是带 SSL 的 WebSocket,而微信小程序中不允许使用带端口的 wss 连接,只能使用 443 端口.想使用其他端口就需要在 ...
- uniapp 小程序 flex布局 v-for 4栏展示
注:本项目的图片资源来源于后端接口,所以使用的是v-for. 关键词:uniapp 小程序 flex布局 v-for 4栏展示 自适应 <view style="display: fl ...
- 微信小程序简单封装图片上传组件
微信小程序简单封装图片上传组件 希望自己 "day day up" -----小陶 我从哪里来 在写小程序的时候需要上传图片,个人觉得官方提供的 Uploader 组件不是太好用, ...
- uniapp小程序迁移到TS
uniapp小程序迁移到TS 我一直在做的小程序就是 山科小站 也已经做了两年了,目前是用uniapp构建的,在这期间也重构好几次了,这次在鹅厂实习感觉受益良多,这又得来一次很大的重构,虽然小程序功能 ...
- 关于小程序websocket全套解决方案,Nginx代理wss
需求对话 提问 我在本地web能够使用ws协议去链接websocket,但是小程序不能使用. 回答 由于小程序使用的是SSL加密协议,所以需要使用wss.这里wss与ws的关系就相当于https于ht ...
- 小程序websocket心跳库——websocket-heartbeat-miniprogram
前言 在16年的时候因为项目接触到websocket,而后对心跳重连做了一次总结,写了篇博客,而后18年对之前github上的demo代码进行了再次开发和开源,最终封装成库.如下: 博客:https: ...
- 快速上手微信小程序webSocket
WebSocket是一种在单个TCP连接上进行全双工通信的协议.WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范.WebSocket API也被W3 ...
随机推荐
- ES7中前端异步特性:async、await。
在最新的ES7(ES2017)中提出的前端异步特性:async.await. 什么是async.await? async顾名思义是"异步"的意思,async用于声明一个函数是异步的 ...
- Java安全之Commons Collections6分析
Java安全之Commons Collections6分析 0x00 前言 其实在分析的几条链中都大致相同,都是基于前面一些链的变形,在本文的CC6链中,就和前面的有点小小的区别.在CC6链中也和CC ...
- Figma禁封中国企业,下一个会是Postman吗?国产软件势在必行!
"新冷战"蔓延到生产力工具 著名 UI 设计软件 Figma 宣布制裁大疆! 近日,网上流传一份 Figma 发送给大疆的内部邮件.其中写道: "我们了解到,大疆在美 ...
- 内网穿透NPS
内网穿透实现 nps文档 https://ehang-io.github.io/nps/#/install nps docker镜像 https://hub.docker.com/r/ffdfgdfg ...
- 2021.08.09 P4868 Preprefix sum(树状数组)
2021.08.09 P4868 Preprefix sum(树状数组) P4868 Preprefix sum - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 题意: 前缀和(pr ...
- python中一些列表知识
列表 序列是 Python 中最基本的数据结构. 序列中的每个值都有对应的位置值,称之为索引,第一个索引是 0,第二个索引是 1,依此类推. Python 有 6 个序列的内置类型,但最常见的是列表和 ...
- docker基础_数据卷
docker数据卷 为什么要使用数据卷 如果数据都在容器中,那么容器一旦删除,数据就会丢失!docker容器需要将产生的数据同步到本地.容器与容器之间也需要有一个数据共享的技术 将某些文件共享.这就是 ...
- 【虚拟机】VMware-open-vm-tools安装
open-vm-tools(VMware-tools的进化版) VMware Tool 和 open-vm-tools任选一样安装即可 在终端进入超级用户 换源下载,依次输入下面命令 sudo cp ...
- JDK内置锁深入探究
一.序言 本文讲述仅针对 JVM 层次的内置锁,不涉及分布式锁. 锁有多种分类形式,比如公平锁与非公平锁.可重入锁与非重入锁.独享锁与共享锁.乐观锁与悲观锁.互斥锁与读写锁.自旋锁.分段锁和偏向锁/轻 ...
- 使用aspnetcore前后端分离开发,你一定要知道这个
前言 用过Vue单页面应用开发的,一定都知道Vue-router这个路由组件,它支持hash和history两种模式. HTML5 History 模式 vue-router 默认 hash 模式 - ...