websocketStore.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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'));
  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. }) {
  68. // console.log('WebSocket连接错误')
  69. },
  70. websocketClose({
  71. state
  72. }) {
  73. if (!state.socketTask) return
  74. state.socketTast.close({
  75. success(res) {
  76. // console.log('关闭成功', res)
  77. },
  78. fail(err) {
  79. // console.log('关闭失败', err)
  80. }
  81. })
  82. },
  83. // 发送数据
  84. websocketSend({
  85. state
  86. }, data) {
  87. uni.sendSocketMessage({
  88. data,
  89. success: res => {
  90. // console.log('发送成功', res)
  91. },
  92. fail: e => {
  93. // console.log('发送失败', e)
  94. }
  95. })
  96. }
  97. }
  98. })
  99. export default store