websocketStore.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. const store = new Vuex.Store({
  5. state: {
  6. socketTask: null,
  7. websocketData: {}, // 存放从后端接收到的websocket数据
  8. },
  9. mutations: {
  10. setWebsocketData(state, data) {
  11. state.websocketData = data
  12. }
  13. },
  14. actions: {
  15. websocketInit({
  16. state,
  17. dispatch
  18. }, url) {
  19. state.socketTask = uni.connectSocket({
  20. url, // url是websocket连接ip
  21. success: () => {
  22. console.log('WebSocket连接成功!')
  23. },
  24. fail: e => {
  25. setTimeout(() => {
  26. dispatch('websocketInit', url)
  27. }, 3000)
  28. console.log('连接失败' + e)
  29. }
  30. })
  31. state.socketTask.onOpen(() => dispatch('websocketOnOpen'))
  32. state.socketTask.onMessage(res => dispatch('websocketOnMessage', res))
  33. state.socketTask.onClose(e => dispatch('websocketOnClose', url));
  34. state.socketTask.onError(e => dispatch('websocketOnError', url));
  35. },
  36. websocketOnOpen({
  37. commit
  38. }) {
  39. console.log('WebSocket连接正常打开中...!')
  40. },
  41. // 收到数据
  42. websocketOnMessage({
  43. commit
  44. }, res) {
  45. let data;
  46. try {
  47. data = JSON.parse(res.data)
  48. } catch {
  49. data = {
  50. content: res.data
  51. }
  52. }
  53. commit('setWebsocketData', data);
  54. },
  55. websocketOnClose({
  56. commit,
  57. dispatch
  58. }, url) {
  59. setTimeout(() => {
  60. dispatch('websocketInit', url)
  61. }, 3000)
  62. console.log('WebSocket连接关闭')
  63. },
  64. websocketOnError({
  65. commit,
  66. dispatch
  67. }, url) {
  68. dispatch('websocketClose')
  69. setTimeout(() => {
  70. dispatch('websocketInit', url)
  71. }, 3000)
  72. console.log('WebSocket连接错误')
  73. },
  74. websocketClose({
  75. state
  76. }) {
  77. if (!state.socketTask) return
  78. state.socketTast.close({
  79. success(res) {
  80. console.log('关闭成功', res)
  81. },
  82. fail(err) {
  83. console.log('关闭失败', err)
  84. }
  85. })
  86. },
  87. // 发送数据
  88. websocketSend({
  89. state
  90. }, data) {
  91. uni.sendSocketMessage({
  92. data,
  93. success: res => {
  94. console.log('发送成功', res)
  95. },
  96. fail: e => {
  97. console.log('发送失败', e)
  98. }
  99. })
  100. }
  101. }
  102. })
  103. export default store