当前位置:   article > 正文

关于websocket 在vue和react中的使用_websocket react前端怎么连wss

websocket react前端怎么连wss

1、在vue中使用

1、初始化

  1. initWebSocket: function () {
  2. // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
  3. // 用户token
  4. let token= getToken()
  5. if (token=== 'undefined' || !token) {
  6. token= ''
  7. }
  8. let url = ''
  9. if (process.env.NODE_ENV === 'production') {
  10. // 生产环境
  11. url = ''
  12. } else if (process.env.NODE_ENV === 'staging') {
  13. url = '' // 测试服
  14. } else {
  15. // development 开发环境
  16. url = ''
  17. }
  18. this.websock = new WebSocket(url)
  19. this.websock.onopen = this.websocketOnopen
  20. this.websock.onerror = this.websocketOnerror
  21. this.websock.onmessage = this.websocketOnmessage
  22. this.websock.onclose = this.websocketOnclose
  23. },

2、开始连接

  1. websocketOnopen: function () {
  2. console.log('WebSocket连接成功')
  3. //心跳检测重置
  4. // this.heartCheck.reset().start()
  5. //开启心跳
  6. this.start()
  7. },

3、心跳监测

  1. start() {
  2. //开启心跳
  3. let context = this
  4. clearInterval(context.timeObj)
  5. context.timeObj = setInterval(function () {
  6. //这里发送一个心跳,后端收到后,返回一个心跳消息
  7. // console.log('心跳', context.websock)
  8. if (context.websock.readyState === 1) {
  9. //如果连接正常
  10. context.websock.send(JSON.stringify({ content: 'user-bind心跳包', type: 0 }))
  11. } else {
  12. //否则重连
  13. context.reconnect()
  14. }
  15. }, context.timeout)
  16. },

4、连接失败

  1. // 连接失败后的回调函数
  2. websocketOnerror: function (e) {
  3. console.log('WebSocket连接发生错误', e)
  4. this.reconnect()
  5. },

5、从服务器接受到信息

  1. websocketOnmessage: function (e) {
  2. // console.log('监听关闭' + e)
  3. console.log('-----接收消息-------', e)
  4. // 收到消息,添加报警声音(先判断声音报警是否开启)
  5. if (this.pcAlarmVoice) {
  6. this.alarmTime = 5
  7. }
  8. const h = this.$createElement // 创建节点
  9. let alarmData = JSON.parse(e.data).bindContent
  10. alarmData.alarmTime = parseTime(alarmData.alarmTime)
  11. alarmData.alarmType = this.alarmType[alarmData.alarmType]
  12. alarmData.groupName = alarmData.groupName ? alarmData.groupName : '未分配'
  13. let title = alarmData.deviceName + '(' + alarmData.deviceSerial + ')'
  14. // 当前弹窗要插入数组的下标
  15. let index = this.alarmBox.length
  16. if (index === 3) {
  17. this.alarmBox[0].close()
  18. this.alarmBox.pop()
  19. }
  20. let messageHTML = null
  21. if (alarmData.channelName) {
  22. messageHTML = h(
  23. 'div',
  24. {
  25. class: 'alarm-box'
  26. },
  27. [
  28. h('p', this.$t('device.d409') + ':' + alarmData.alarmType),
  29. h('p', this.$t('device.d746') + ':' + alarmData.channelName),
  30. h('p', this.$t('monitor.m15') + ':' + alarmData.groupName),
  31. h('p', this.$t('device.d497') + ':' + alarmData.alarmTime),
  32. h('p', this.$t('user.u258') + ':' + alarmData.alarmContent.cn),
  33. h(
  34. 'div',
  35. {
  36. class: 'btn-box'
  37. },
  38. [
  39. h(
  40. 'button',
  41. {
  42. class: 'btn el-button--primary ' + alarmData.alarmBTN,
  43. on: {
  44. click: () => this.notifyClick(alarmData) // 按钮的点击事件
  45. }
  46. },
  47. '查看详情'
  48. )
  49. ]
  50. )
  51. ]
  52. )
  53. } else {
  54. messageHTML = h(
  55. 'div',
  56. {
  57. class: 'alarm-box'
  58. },
  59. [
  60. h('p', this.$t('device.d409') + ':' + alarmData.alarmType),
  61. h('p', this.$t('user.u489') + ':' + alarmData.objectName),
  62. h('p', this.$t('device.d497') + ':' + alarmData.alarmTime),
  63. h('p', this.$t('user.u258') + ':' + alarmData.alarmContent.cn),
  64. h(
  65. 'div',
  66. {
  67. class: 'btn-box'
  68. },
  69. [
  70. h(
  71. 'button',
  72. {
  73. class: 'btn el-button--primary ' + alarmData.alarmBTN,
  74. on: {
  75. click: () => this.notifyClick(alarmData) // 按钮的点击事件
  76. }
  77. },
  78. this.$t('global.detailBtn') // '查看详情'
  79. )
  80. ]
  81. )
  82. ]
  83. )
  84. }
  85. this.open(title, messageHTML, index)
  86. },
  87. //制作弹窗
  88. open(title, messageHTML, index) {
  89. this.alarmBox[index] = this.$notify({
  90. title: title,
  91. dangerouslyUseHTMLString: true,
  92. duration: 5000, // 自动关闭的时间
  93. // duration: 0, // 不自动关闭
  94. customClass: 'alarm-notify',
  95. // position: 'bottom-right',
  96. message: messageHTML
  97. })
  98. },

6、连接关闭

  1. websocketOnclose: function (e) {
  2. // console.log('WebSocket连接关闭')
  3. // console.log(e)
  4. // if (localStorage.getItem('websocket') === 'screen') {
  5. // return false
  6. // }
  7. // this.reconnect()
  8. },

7、发送心跳

  1. websocketSend(text) {
  2. // 数据发送
  3. try {
  4. this.websock.send(text)
  5. } catch (err) {
  6. // console.log('send failed (' + err.code + ')')
  7. }
  8. },

8、重新连接函数

  1. reconnect() {
  2. let context = this
  3. if (context.lockReconnect) return
  4. context.lockReconnect = true
  5. //没连接上会一直重连,设置延迟避免请求过多
  6. clearTimeout(this.time1)
  7. this.time1 = setTimeout(function () {
  8. // console.info('尝试重连...')
  9. context.initWebSocket()
  10. context.lockReconnect = false
  11. }, 5000)
  12. },

9、页面销毁时

  1. beforeDestroy() {
  2. // localStorage.setItem('websocket', 'screen')
  3. this.websock.close()
  4. this.websock = null
  5. clearInterval(this.timeObj)
  6. clearTimeout(this.time1)
  7. // console.log('断开网页websock连接')
  8. }

10、同时添加一个报警弹窗

  1. <!-- 报警时的声音 controls -->
  2. <audio
  3. loop="true"
  4. ebkit-playsinline="true"
  5. playsinline="true"
  6. ref="myAudio"
  7. src="../../assets/alarm.mp3"
  8. ></audio>
  9. watch: {
  10. alarmTime(after) {
  11. clearInterval(this.timer)
  12. if (after > 0) {
  13. this.setAudio()
  14. } else {
  15. this.myAudio.pause() // 暂停
  16. clearInterval(this.timer)
  17. }
  18. }
  19. },

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

闽ICP备14008679号