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

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

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

javascript 复制代码
<template>
  <div></div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
const person = reactive({});
const wsConnections = ref([]);
onMounted(() => {
  //初始化创建一个ip数组 遍历过后调用创建十个sokect实例
  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)
  );
  //以上是针对初始化创建十个soket  如初始化只创建一个sokey只需直接new实例就行
//   new WebSocketConnection(传入ip)  //只创建一个连接
});
class WebSocketConnection {
  constructor(url, index) {
    //连接的url地址
    this.url = url;
    this.ws = new WebSocket(url);
    this.bindEvents(); //创建实例过后的回调
  }
  //监听回调(连接成功、错误、断开、接收消息)
  bindEvents() {
    this.ws.onopen = () => {
      console.log(`${this.url} 连接成功.`);
    };

    this.ws.onerror = (error) => {
      console.error(`连接错误 ${this.url}: ${error}`);
    };

    this.ws.onclose = (e) => {
      console.log(`${this.url} 连接关闭`);
      if (e.code !== 1000) {
        console.log(`Reconnecting ${this.url}...`);
        //重连 此处可以加个setTimeout 多少秒后再重连
        this.reconnect();
      }
    };
  }
  //重连
  reconnect() {
    this.ws = new WebSocket(this.url);
    this.bindEvents();
  }
}
</script>
<style scoped lang='less'>
</style>

2.定时给后端发送消息

javascript 复制代码
<template>
  <div></div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
const person = reactive({});
const wsConnections = ref([]);
onMounted(() => {
  //初始化创建一个ip数组 遍历过后调用创建十个sokect实例
  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)
  );
  //以上是针对初始化创建十个soket  如初始化只创建一个sokey只需直接new实例就行
  //   new WebSocketConnection(传入ip)  //只创建一个连接
});
class WebSocketConnection {
  constructor(url, index) {
    //连接的url地址
    this.url = url;
    this.ws = new WebSocket(url);
    this.bindEvents(); //创建实例过后的回调
    this.startSending(); //给后端发送消息
  }
  //监听回调(连接成功、错误、断开、接收消息)
  bindEvents() {
    this.ws.onopen = () => {
      console.log(`${this.url} 连接成功.`);
    };

    this.ws.onerror = (error) => {
      console.error(`连接错误 ${this.url}: ${error}`);
    };

    this.ws.onclose = (e) => {
      console.log(`${this.url} 连接关闭`);
      if (e.code !== 1000) {
        console.log(`Reconnecting ${this.url}...`);
        //重连 此处可以加个setTimeout 多少秒后再重连
        this.reconnect();
      }
    };
  }
  //重连
  reconnect() {
    this.ws = new WebSocket(this.url);
    this.bindEvents();
  }
  //   给后端发送消息
  startSending() {
    this.interval = setInterval(() => {
      if (this.ws.readyState === WebSocket.OPEN) {
        this.ws.send("发给后端的");
      }
    }, 5000);
  }
  //   停止发消息时调用
  stopSending() {
    clearInterval(this.interval);
  }
}
onUnmounted(() => {
  wsConnections.value.forEach((connection) => {
    connection.stopSending(); // 停止定时消息
    connection.ws.close(); // 关闭WebSocket连接
  });
});
</script>
<style scoped lang='less'>
</style>

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

javascript 复制代码
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:
javascript 复制代码
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的消息:

javascript 复制代码
<template>
  <div>
    Received Message: {{ message }}
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const message = computed(() => store.state.messages[0]) // 获取第一个消息
 
</script>

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

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

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

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

javascript 复制代码
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();  
      });
    });

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

javascript 复制代码
<template>
  <div>
    Received Message: {{ message }}
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useUsersStore } from "@/store/user.js";

    const store = useUsersStore ()
    const message = computed(() => store.messages[0]) // 使用第一条消息

</script>
相关推荐
博客zhu虎康7 分钟前
ElementUI 的 form 表单校验
前端·javascript·elementui
蜗牛hb7 分钟前
VMware Workstation虚拟机网络模式
开发语言·学习·php
汤姆和杰瑞在瑞士吃糯米粑粑23 分钟前
【C++学习篇】AVL树
开发语言·c++·学习
Biomamba生信基地30 分钟前
R语言基础| 功效分析
开发语言·python·r语言·医药
手可摘星河32 分钟前
php中 cli和cgi的区别
开发语言·php
CodeClimb1 小时前
【华为OD-E卷-木板 100分(python、java、c++、js、c)】
java·javascript·c++·python·华为od
咸鱼翻面儿1 小时前
Javascript异步,这次我真弄懂了!!!
javascript
CT随1 小时前
Redis内存碎片详解
java·开发语言
anlog1 小时前
C#在自定义事件里传递数据
开发语言·c#·自定义事件
奶香臭豆腐1 小时前
C++ —— 模板类具体化
开发语言·c++·学习