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

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

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

<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.定时给后端发送消息

<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 其他组件只使用第一个链接的数据

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的消息:

<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将十个链接收到的数据全部存了 其他组件只使用第一个链接的数据

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();  
      });
    });

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

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_63701303

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值