当前位置:   article > 正文

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

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

websocket 封装

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

  1. class websocketUtils {
  2. constructor(openId, time) {
  3. this.url = `wss://****` //ws地址 拼接一下 此处用的是openId
  4. this.data = null
  5. this.isOpenSocket = false //避免重复连接
  6. this.timeout = time //隔多久执行检测 单位秒(s)
  7. this.heartbeatInterval = null //检测服务器端是否还存活
  8. this.reconnectTimeOut = null //重连之后隔多久才再次重连
  9. try {
  10. return this.connectSocketInit()
  11. } catch (e) {
  12. console.log('===========连接错误捕获catch====================',e);
  13. this.isOpenSocket = false
  14. this.reconnect();
  15. }
  16. }
  17. // 创建websocket连接
  18. connectSocketInit() {
  19. this.socketTask = uni.connectSocket({
  20. url: this.url,
  21. header: {
  22. //头部可以添加所需字段如token
  23. 'content-type': 'application/json'
  24. },
  25. success:()=>{
  26. console.log("============正准备建立websocket中================");
  27. // 返回实例
  28. return this.socketTask
  29. },
  30. });
  31. this.socketTask.onOpen((res) => {
  32. console.log("==============WebSocket连接正常=============");
  33. clearTimeout(this.reconnectTimeOut)
  34. clearInterval(this.heartbeatInterval)
  35. this.isOpenSocket = true;
  36. this.start();
  37. // 只有连接正常打开中 ,才能正常收到消息
  38. this.socketTask.onMessage((res) => {
  39. console.log(res.data,'===============接收===onMessage===============')
  40. //全局注册uniapp事件,在任何页面都能接受到
  41. uni.$emit('socketMessage', res)
  42. });
  43. })
  44. // 监听失败,再次打开 判断主动重连
  45. // uni.onSocketError((res) => {
  46. // console.log('==========WebSocket连接打开失败哦===============');
  47. // this.isOpenSocket = false;
  48. // this.reconnect();
  49. // });
  50. // socket关闭了会执行 此处
  51. this.socketTask.onClose((e) => {
  52. console.log("========已经被关闭了====================",e)
  53. this.isOpenSocket = false;
  54. // 加了flag判断是否为手动(用户主动关闭)
  55. e && e.reason == 'user' ? '' : this.reconnect();
  56. })
  57. }
  58. //发送消息
  59. send(value){
  60. // 连接正常打开时 ,才能正常成功发送消息
  61. this.socketTask.send({
  62. data: value,
  63. async success() {
  64. console.log("===========消息发送成功===============");
  65. },
  66. });
  67. }
  68. //开启心跳检测
  69. start(){
  70. this.data={value:"发送心跳内容",method:"发送心跳方法名称"}
  71. this.heartbeatInterval = setInterval(()=>{
  72. console.log('======start====开启心跳检测====',this.data)
  73. this.send(JSON.stringify(this.data));
  74. },this.timeout * 1000)
  75. }
  76. //重新连接
  77. reconnect(){
  78. //停止发送心跳
  79. clearInterval(this.heartbeatInterval)
  80. //如果不是人为关闭的话,进行重连
  81. if(!this.isOpenSocket ){
  82. this.reconnectTimeOut = setTimeout(()=>{
  83. this.connectSocketInit();
  84. },3000)
  85. }
  86. }
  87. // 关闭 WebSocket 连接
  88. closeSocket(reason = '关闭') {
  89. const _this = this
  90. this.socketTask.close({
  91. reason,
  92. success() {
  93. _this.data = null
  94. _this.isOpenSocket = false
  95. _this.socketTask = null
  96. clearTimeout(_this.reconnectTimeOut)
  97. clearInterval(_this.heartbeatInterval)
  98. console.log('===============关闭 WebSocket 成功===================')
  99. },
  100. fail() {
  101. console.log('===================关闭 WebSocket 失败=====================')
  102. }
  103. })
  104. }
  105. //将获取的消息导出外部
  106. exportMessage(callback) {
  107. this.socketTask.onMessage((res) => {
  108. console.log(res,'===============exportMessage============')
  109. return callback(res)
  110. })
  111. }
  112. }
  113. module.exports = websocketUtils

页面引入使用 

全局引入:

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

  1. //引入websocket文件
  2. import websocketUtils from '@/utils/websocketUtils.js'
  3. //挂载并开启websocket
  4. Vue.prototype.$socketUtils = new websocketUtils("*******",10)

 2.指定页面中使用

  1. // 发送消息
  2. let data={value:"发送的value"}
  3. this.$socketUtils.send(JSON.stringify(data));
  4. // 接收消息
  5. this.$socketUtils.exportMessage(res=>{
  6. console.log(res);
  7. })
 单页面使用引入:
  1. <!-- 页面 -->
  2. <template>
  3. <view class='e-about-operation-wrap'>
  4. </view>
  5. </template>
  6. <script>
  7. import websocketUtils from '@/utils/websocketUtils.js'
  8. const app = getApp()
  9. export default {
  10. name: 'ESign',
  11. components: {},
  12. data() {
  13. return { };
  14. },
  15. onLoad: function(option) {
  16. },
  17. onShow: function() {
  18. //在uniapp全局中定义了socketWBObj变量
  19. app.globalData.socketWBObj = new websocketUtils(this.user.loginInfo.openId,10)
  20. //监听获取消息
  21. uni.$on('socketMessage', this.wbSocketGetMsg)
  22. //方法获取收到的消息
  23. app.globalData.socketWBObj.exportMessage(res => {
  24. console.warn(res);
  25. })
  26. },
  27. onHide: function() {
  28. },
  29. onUnload(e) {
  30. },
  31. created() {},
  32. mounted() {
  33. },
  34. methods: {
  35. wbSocketGetMsg(res){
  36. const _this = this
  37. console.log(res,'======wbSocketGetMsg==========')
  38. // 关闭连接
  39. if (app.globalData.socketWBObj) {
  40. app.globalData.socketWBObj.closeSocket('user')
  41. }
  42. }
  43. },
  44. watch: {},
  45. computed: {},
  46. }
  47. </script>
  48. <style lang='scss' scoped>
  49. .e-about-operation-wrap{
  50. }
  51. </style>

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号