同时创建多个websoket(初始化多个连接、断开的重连、每个连接定时发消息、每个连接存储接收的数据(vuex或者pinia))

可复制现成代码直接使用!!

1.下边的例子演示了创建10个WebSocket 实例,当其中某一个连接失败时,会自动进行重连




2.定时给后端发送消息




2.将十个链接收到的数据全部存在vuex 其他组件只使用第一个链接的数据

import { createStore } from 'vuex'

export default createStore({
  state: {
    messages: []
  },
  mutations: {
    setMessages(state, payload) {
      // 我们这里假设payload的格式为 { index: n, message: msg }
      state.messages[payload.index] = payload.message
    },
  },
  actions: {
  }
})
修改WebSocketConnection 类,使其接收到消息的时候调用 setMessages mutation:
import { ref, onMounted, onUnmounted } from 'vue';
import store from '@/store'

class WebSocketConnection {
  constructor(url, index) {
    this.url = url;
    this.index = index;
    this.ws = new WebSocket(url);
    this.bindEvents();
    this.startSending();
  }

  bindEvents() {
    // ...其它代码略 看上面

    this.ws.onmessage = (message) => {
      // 当接收到数据时,将数据保存到 Vuex
      store.commit('setMessages', { index: this.index, message: message.data });
    };
  }
  // ...其它代码略 看上面
}

// 在 onMounted 钩子函数中创建WebSocket连接
onMounted(() => {
    const urls = ['wss://url1', 'wss://url2', 'wss://url3', 'wss://url4', 'wss://url5', 'wss://url6', 'wss://url7', 'wss://url8', 'wss://url9', 'wss://url10'];
    wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
});

然后,在其他组件中以这种方式使用第一个Websocket的消息:



3.使用pinia将十个链接收到的数据全部存了 其他组件只使用第一个链接的数据

import { defineStore } from "pinia"
export const useUsersStore = defineStore('users', {
    // 其它配置项
    state: () => {
        return {
            messages: [],
        };
    },
    getters: {

    },
    actions: {
        setMessage(payload) {
            this.messages[payload.index] = payload.messages
        }
    }
})

然后,在 WebSocketConnection 类中调用 setMessage 来储存数据:

import { ref, onMounted, onUnmounted } from 'vue';
import { useUsersStore } from "@/store/user.js";

class WebSocketConnection {
  constructor(url, index) {
    this.url = url;
    this.index = index;
    this.ws = new WebSocket(url);
    this.store = useUsersStore();
    this.bindEvents();
    this.startSending();
  }

  bindEvents() {
    // ...同上面

    this.ws.onmessage = (message) => {
      // 收到信息后,将其存储在Pinia中
      this.store.setMessage({ index: this.index, message: message.data });
    };
    
  }
  // ...同上面e...
}
  onMounted(() => {
      const urls = ['ws://url1', 'ws://url2', 'ws://url3', 'ws://url4', 'ws://url5', 
                    'ws://url6', 'ws://url7', 'ws://url8', 'ws://url9', 'ws://url10'];
      wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
    });

    onUnmounted(() => {
      wsConnections.value.forEach(connection => {
        connection.stopSending();  
        connection.ws.close();  
      });
    });

然后在其他组件中可以像这样使用第一个连接收到的数据:



你可能感兴趣的:(websoket,javascript,开发语言,ecmascript)