websocket.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. export default {
  2. namespaced: true,
  3. state: {
  4. websock: {},
  5. url: '',
  6. lockReconnect: false, // 是否真正建立连接
  7. timeout: 30 * 1000, // 30秒一次心跳
  8. timeoutObj: {}, // 心跳心跳倒计时
  9. serverTimeoutObj: {}, // 心跳倒计时
  10. timeoutnum: {}, // 断开 重连倒计时
  11. message: {}
  12. },
  13. getters: {
  14. message (state) {
  15. return state.message
  16. }
  17. },
  18. mutations: {
  19. WEBSOCKET_INIT (state, url) {
  20. if (!state || !url) return
  21. let that = this
  22. state.websock = new WebSocket(url)
  23. state.url = url
  24. state.websock.onopen = () => {
  25. console.log('连接成功')
  26. // 发送心跳包
  27. that.commit('websocket/start')
  28. }
  29. state.websock.onmessage = (callBack) => {
  30. // 重置心跳
  31. // console.log('callBack = ' + callBack.data)
  32. that.commit('websocket/reset')
  33. if (callBack.data === 'heartCheck') {
  34. return
  35. }
  36. state.message = callBack.data
  37. }
  38. state.websock.onerror = () => { // e错误
  39. console.log('onerror')
  40. that.commit('websocket/reconnect')
  41. }
  42. state.websock.onclose = () => { // e关闭
  43. console.log('onclose')
  44. that.commit('websocket/reconnect')
  45. }
  46. },
  47. WEBSOCKET_SEND (state, message) {
  48. state.websock.send(message)
  49. },
  50. reconnect (state) { // 重新连接
  51. let that = this
  52. if (state.lockReconnect) {
  53. return
  54. }
  55. state.lockReconnect = true
  56. // 没连接上会一直重连,设置延迟避免请求过多
  57. state.timeoutnum && clearTimeout(state.timeoutnum)
  58. state.timeoutnum = setTimeout(() => {
  59. // 新连接
  60. that.commit('websocket/WEBSOCKET_INIT', state.url)
  61. state.lockReconnect = false
  62. }, 15000)
  63. },
  64. reset (state) { // 重置心跳
  65. // 清除时间
  66. clearTimeout(state.timeoutObj)
  67. clearTimeout(state.serverTimeoutObj)
  68. // 心跳
  69. this.commit('websocket/start')
  70. },
  71. start (state) {
  72. // 开启心跳
  73. let that = this
  74. state.timeoutObj && clearTimeout(state.timeoutObj)
  75. state.serverTimeoutObj && clearTimeout(state.serverTimeoutObj)
  76. state.timeoutObj = setTimeout(() => {
  77. // 这里发送一个心跳,后端收到后,返回一个心跳消息,
  78. // console.log(state.websock)
  79. if (state.websock.readyState === 1) { // 如果连接正常
  80. state.websock.send('heartCheck')
  81. } else { // 否则重连
  82. that.commit('websocket/reconnect')
  83. }
  84. state.serverTimeoutObj = setTimeout(() => {
  85. // 超时关闭
  86. state.websock.close()
  87. }, state.timeout)
  88. }, state.timeout)
  89. }
  90. },
  91. actions: {
  92. WEBSOCKET_INIT ({
  93. commit
  94. }, url) {
  95. commit('WEBSOCKET_INIT', url)
  96. },
  97. WEBSOCKET_SEND ({
  98. commit
  99. }, message) {
  100. commit('WEBSOCKET_SEND', message)
  101. }
  102. }
  103. }