websocketStore.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. is_open_socket = false //避免重复连接
  9. },
  10. mutations: {
  11. setWebsocketData(state, data) {
  12. state.websocketData = data
  13. }
  14. },
  15. actions: {
  16. websocketInit({
  17. state,
  18. dispatch
  19. }, url) {
  20. state.socketTask = uni.connectSocket({
  21. url, // url是websocket连接ip
  22. success: () => {
  23. console.log('WebSocket连接成功!')
  24. },
  25. fail: e => {
  26. console.log('连接失败' + e)
  27. }
  28. })
  29. state.socketTask.onOpen(() => dispatch('websocketOnOpen'))
  30. state.socketTask.onMessage(res => dispatch('websocketOnMessage', res))
  31. state.socketTask.onClose(e => dispatch('websocketOnClose'))
  32. state.socketTask.onError(e => dispatch('websocketOnError'))
  33. },
  34. websocketOnOpen({
  35. commit
  36. }) {
  37. console.log('WebSocket连接正常打开中...!')
  38. },
  39. // 收到数据
  40. websocketOnMessage({
  41. commit
  42. }, res) {
  43. let data;
  44. try {
  45. data = JSON.parse(res.data)
  46. } catch {
  47. data = {
  48. content: res.data
  49. }
  50. }
  51. commit('setWebsocketData', data);
  52. },
  53. websocketOnClose({
  54. commit,
  55. dispatch
  56. }) {
  57. console.log('WebSocket连接关闭')
  58. },
  59. websocketOnError({
  60. commit,
  61. dispatch
  62. }) {
  63. console.log('WebSocket连接错误')
  64. },
  65. websocketClose({
  66. state
  67. }) {
  68. if (!state.socketTask) return
  69. state.socketTast.close({
  70. success(res) {
  71. console.log('关闭成功', res)
  72. },
  73. fail(err) {
  74. console.log('关闭失败', err)
  75. }
  76. })
  77. },
  78. // 发送数据
  79. websocketSend({
  80. state
  81. }, data) {
  82. uni.sendSocketMessage({
  83. data,
  84. success: res => {
  85. console.log('发送成功', res)
  86. },
  87. fail: e => {
  88. console.log('发送失败', e)
  89. }
  90. })
  91. }
  92. }
  93. })
  94. export default store