this.beforeunloadHandler(e)) 然后调用this.webstock.close()关闭socket的长链接。WebSocket连接发生错误的时候,连接错误 需要重连this.reConnect(),尝试重新连接,本次重连次数大于6次就不连接了,放弃连接。三、功能点三WebSocket连接发生错误的时候,连接错误 需要重连。_we">
当前位置:   article > 正文

websocket每隔5秒给服务端send一次信息_websocket后台给前端发消息频率

websocket后台给前端发消息频率

websocket轮询每隔5秒给服务端send一次信息,主要功能点如下:

  1. socket 采用了定时器 setInterval() 需要清除定时器否则会报错

  1. 监听了突然关闭浏览器窗口,destroyed里面直接监听 window.removeEventListener("beforeunload", e => this.beforeunloadHandler(e)) 然后调用this.webstock.close()关闭socket的长链接。

  1. WebSocket连接发生错误的时候,连接错误 需要重连this.reConnect(),尝试重新连接,本次重连次数大于6次就不连接了,放弃连接。

先上效果图:

一 、功能点一清除定时器:

clearInterval(this.timer) // 清除定时器

二、功能点二监听了突然关闭浏览器窗口:

  1. mounted() {
  2. window.addEventListener("beforeunload", e => this.beforeunloadHandler(e))
  3. window.addEventListener("unload", e => this.unloadHandler(e))
  4. },
  1. beforeunloadHandler() {
  2. this._beforeUnload_time = new Date().getTime();
  3. },
  4. unloadHandler(e) {
  5. this._gap_time = new Date().getTime() - this._beforeUnload_time;
  6. // debugger
  7. // 关闭或刷新窗口都保存数据到后台
  8. // 判断窗口是关闭还是刷新
  9. if (this._gap_time <= 5) {
  10. // 关闭连接
  11. this.webstock.close()
  12. }
  13. }
  1. destroyed() {
  2. this.$destroy()
  3. clearInterval(this.timer) // 清除定时器
  4. // 页面销毁时关闭长连接
  5. // if (this.webstock !== null) {
  6. // this.webstock.close()
  7. // }
  8. window.removeEventListener("beforeunload", e => this.beforeunloadHandler(e))
  9. window.removeEventListener("unload", e => this.unloadHandler(e))
  10. }

三、功能点三WebSocket连接发生错误的时候,连接错误 需要重连

  1. websocketonerror(e) {
  2. console.log("WebSocket连接发生错误")
  3. // 连接断开后修改标识
  4. this.isConnect = false
  5. // 连接错误 需要重连
  6. this.reConnect()
  7. }
  8. },

全部代码如下:

  1. <template>
  2. </template>
  3. <script>
  4. export default {
  5. data() {
  6. return {
  7. timer: 5000,
  8. webstock: '', // webSocket使用
  9. isConnect: false, // webSocket连接标识 避免重复连接
  10. reConnectNum: 1, // 断开后重新连接的次数 免得后台挂了,前端一直重连
  11. _beforeUnload_time: null,
  12. _gap_time: null
  13. }
  14. },
  15. methods: {
  16. /*webSocket start*/
  17. initWebSocket() {
  18. let userId = this.$store.state.user.userId
  19. if (userId !== null && userId !== '') {
  20. // WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
  21. // 本地环境
  22. // let wsServer =
  23. // `${
  24. // location.protocol === "https" ? "wss" : "ws"
  25. // }://localhost:9106/接口前缀/websocket/` + userId;
  26. // 线上环境
  27. let wsServer = 'ws://172.16.0.54:8102/api/webSocket/' + userId
  28. console.log("wsServer:", wsServer)
  29. this.webstock = new WebSocket(wsServer)
  30. this.webstock.onopen = this.websocketonopen
  31. this.webstock.onerror = this.websocketonerror
  32. this.webstock.onmessage = this.websocketonmessage
  33. this.webstock.onclose = this.websocketclose
  34. }
  35. },
  36. websocketonopen() {
  37. console.log("WebSocket连接成功")
  38. // 连接建立后修改标识
  39. this.isConnect = true
  40. const timeoutInfoId = '420507657544310784'
  41. clearInterval(this.timer) // 清除定时器
  42. const that = this
  43. setInterval(() => {
  44. if (window.location.pathname === '/standardTemplate') {
  45. that.webstock.send(timeoutInfoId)
  46. }
  47. }, this.timer)
  48. },
  49. websocketonerror(e) {
  50. console.log("WebSocket连接发生错误")
  51. // 连接断开后修改标识
  52. this.isConnect = false
  53. // 连接错误 需要重连
  54. // this.reConnect()
  55. if (window.location.pathname === '/standardTemplate') {
  56. this.reConnect()
  57. }
  58. },
  59. // 接收后端推送过来的消息
  60. websocketonmessage(e) {
  61. console.log("message消息:", e.data)
  62. // if (e != null) {
  63. // let str = JSON.parse(e.data)
  64. // }
  65. },
  66. websocketclose(e) {
  67. console.log("webSocket连接关闭")
  68. // 连接断开后修改标识
  69. this.isConnect = false
  70. this.webstock = ''
  71. if (window.location.pathname === '/standardTemplate') {
  72. this.reConnect()
  73. }
  74. },
  75. // 重新连接
  76. reConnect() {
  77. console.log("尝试重新连接,本次重连次数:" + this.reConnectNum)
  78. if (this.reConnectNum > 6) {
  79. return false
  80. }
  81. // 如果已经连上就不再重试了
  82. if (this.isConnect) return
  83. this.initWebSocket()
  84. this.reConnectNum = this.reConnectNum + 1
  85. },
  86. /*webSocket end*/
  87. beforeunloadHandler() {
  88. this._beforeUnload_time = new Date().getTime();
  89. },
  90. unloadHandler(e) {
  91. this._gap_time = new Date().getTime() - this._beforeUnload_time;
  92. // debugger
  93. // 关闭或刷新窗口都保存数据到后台
  94. // 判断窗口是关闭还是刷新
  95. if (this._gap_time <= 5) {
  96. // 关闭连接
  97. this.webstock.close()
  98. }
  99. }
  100. },
  101. created() {
  102. this.reConnectNum = 1
  103. this.initWebSocket()
  104. },
  105. mounted() {
  106. window.addEventListener("beforeunload", e => this.beforeunloadHandler(e))
  107. window.addEventListener("unload", e => this.unloadHandler(e))
  108. },
  109. destroyed() {
  110. this.$destroy()
  111. clearInterval(this.timer) // 清除定时器
  112. // 页面销毁时关闭长连接
  113. // if (this.webstock !== null) {
  114. // this.webstock.close()
  115. // }
  116. window.removeEventListener("beforeunload", e => this.beforeunloadHandler(e))
  117. window.removeEventListener("unload", e => this.unloadHandler(e))
  118. }
  119. }
  120. </script>

问题一、

报错信息如下:socketReport.vue?8285:51 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

要明白这个问题产生的原因,就需要了解websocket的几个状态。通常在实例化一个websocket对象之后,客户端就会与服务器进行连接。但是连接的状态是不确定的,于是用readyState属性来进行标识。它有四个值,分别对应不同的状态:

  1. CONNECTING:值为0,表示正在连接;
  2. OPEN:值为1,表示连接成功,可以通信了;
  3. CLOSING:值为2,表示连接正在关闭;
  4. CLOSED:值为3,表示连接已经关闭,或者打开连接失败。

这样问题的原因就很明显了,之所以数据不能发送出去,是因为websocket还处在“CONNECTING”状态下,连接还没有成功。

解决办法

只要在函数中添加对状态的判断,在状态为OPEN时,执行send方法即可。方法一代码如下

  1. this.init()
  2. if (this.webstock.readyState===1) {
  3. this.webstock.send()
  4. }

问题二、vue项目中监听电脑网络的状态,突然断开网络或者关机

写法一、

  1. data() {
  2. return {
  3. network: true, //默认有网
  4.         }
  5. }
  1. mounted() {
  2. window.addEventListener("online", () => {
  3. console.log("网络已连接:")
  4. this.network = true
  5. })
  6. // 检测断网
  7. window.addEventListener("offline", () => {
  8. console.log("已断网:")
  9. this.network = false
  10. if (this.webstock !== null) {
  11. this.webstock.close()
  12. }
  13. })
  14. }

控制台打印的结果:

断开网络的情况

再次连接网络:

写法二、

  1. data() {
  2. return {
  3. onLine: navigator.onLine,
  4.     }
  5. }
  1. mounted() {
  2. console.log('this.onLine:', this.onLine)
  3. window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
  4. window.addEventListener('unload', e => this.unloadHandler(e))
  5.     }
  1. beforeDestroy(){
  2. window.removeEventListener('online', this.updateOnlineStatus);
  3. window.removeEventListener('offline', this.updateOnlineStatus);
  4. },
  1. // 检测断网
  2. updateOnlineStatus(e) {
  3. const { type } = e
  4. // this.onLine = type === 'online'
  5. if (type === 'online') {
  6. // 网络已连接
  7. console.log("网络已连接:")
  8. this.$emit('fatherMethod')
  9. if (window.location.pathname === '/newReport' || window.location.pathname === '/c3analysis') {
  10. if (!this.unLock){
  11. this.reConnect()
  12. }
  13. }
  14. } else if (type === 'offline') {
  15. // 已断网
  16. console.log("已断网:")
  17. if (this.webstock !== null) {
  18. this.webstock.close()
  19. }
  20. }
  21. },

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/717267
推荐阅读
相关标签
  

闽ICP备14008679号