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


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

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

    1. <script setup>
    2. import { ref, reactive, onMounted } from "vue";
    3. const person = reactive({});
    4. const wsConnections = ref([]);
    5. onMounted(() => {
    6. //初始化创建一个ip数组 遍历过后调用创建十个sokect实例
    7. const urls = [
    8. "wss://url1",
    9. "wss://url2",
    10. "wss://url3",
    11. "wss://url4",
    12. "wss://url5",
    13. "wss://url6",
    14. "wss://url7",
    15. "wss://url8",
    16. "wss://url9",
    17. "wss://url10",
    18. ];
    19. wsConnections.value = urls.map(
    20. (url, index) => new WebSocketConnection(url, index)
    21. );
    22. //以上是针对初始化创建十个soket 如初始化只创建一个sokey只需直接new实例就行
    23. // new WebSocketConnection(传入ip) //只创建一个连接
    24. });
    25. class WebSocketConnection {
    26. constructor(url, index) {
    27. //连接的url地址
    28. this.url = url;
    29. this.ws = new WebSocket(url);
    30. this.bindEvents(); //创建实例过后的回调
    31. }
    32. //监听回调(连接成功、错误、断开、接收消息)
    33. bindEvents() {
    34. this.ws.onopen = () => {
    35. console.log(`${this.url} 连接成功.`);
    36. };
    37. this.ws.onerror = (error) => {
    38. console.error(`连接错误 ${this.url}: ${error}`);
    39. };
    40. this.ws.onclose = (e) => {
    41. console.log(`${this.url} 连接关闭`);
    42. if (e.code !== 1000) {
    43. console.log(`Reconnecting ${this.url}...`);
    44. //重连 此处可以加个setTimeout 多少秒后再重连
    45. this.reconnect();
    46. }
    47. };
    48. }
    49. //重连
    50. reconnect() {
    51. this.ws = new WebSocket(this.url);
    52. this.bindEvents();
    53. }
    54. }
    55. script>
    56. <style scoped lang='less'>
    57. style>

    2.定时给后端发送消息

    1. <script setup>
    2. import { ref, reactive, onMounted, onUnmounted } from "vue";
    3. const person = reactive({});
    4. const wsConnections = ref([]);
    5. onMounted(() => {
    6. //初始化创建一个ip数组 遍历过后调用创建十个sokect实例
    7. const urls = [
    8. "wss://url1",
    9. "wss://url2",
    10. "wss://url3",
    11. "wss://url4",
    12. "wss://url5",
    13. "wss://url6",
    14. "wss://url7",
    15. "wss://url8",
    16. "wss://url9",
    17. "wss://url10",
    18. ];
    19. wsConnections.value = urls.map(
    20. (url, index) => new WebSocketConnection(url, index)
    21. );
    22. //以上是针对初始化创建十个soket 如初始化只创建一个sokey只需直接new实例就行
    23. // new WebSocketConnection(传入ip) //只创建一个连接
    24. });
    25. class WebSocketConnection {
    26. constructor(url, index) {
    27. //连接的url地址
    28. this.url = url;
    29. this.ws = new WebSocket(url);
    30. this.bindEvents(); //创建实例过后的回调
    31. this.startSending(); //给后端发送消息
    32. }
    33. //监听回调(连接成功、错误、断开、接收消息)
    34. bindEvents() {
    35. this.ws.onopen = () => {
    36. console.log(`${this.url} 连接成功.`);
    37. };
    38. this.ws.onerror = (error) => {
    39. console.error(`连接错误 ${this.url}: ${error}`);
    40. };
    41. this.ws.onclose = (e) => {
    42. console.log(`${this.url} 连接关闭`);
    43. if (e.code !== 1000) {
    44. console.log(`Reconnecting ${this.url}...`);
    45. //重连 此处可以加个setTimeout 多少秒后再重连
    46. this.reconnect();
    47. }
    48. };
    49. }
    50. //重连
    51. reconnect() {
    52. this.ws = new WebSocket(this.url);
    53. this.bindEvents();
    54. }
    55. // 给后端发送消息
    56. startSending() {
    57. this.interval = setInterval(() => {
    58. if (this.ws.readyState === WebSocket.OPEN) {
    59. this.ws.send("发给后端的");
    60. }
    61. }, 5000);
    62. }
    63. // 停止发消息时调用
    64. stopSending() {
    65. clearInterval(this.interval);
    66. }
    67. }
    68. onUnmounted(() => {
    69. wsConnections.value.forEach((connection) => {
    70. connection.stopSending(); // 停止定时消息
    71. connection.ws.close(); // 关闭WebSocket连接
    72. });
    73. });
    74. script>
    75. <style scoped lang='less'>
    76. style>

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

    1. import { createStore } from 'vuex'
    2. export default createStore({
    3. state: {
    4. messages: []
    5. },
    6. mutations: {
    7. setMessages(state, payload) {
    8. // 我们这里假设payload的格式为 { index: n, message: msg }
    9. state.messages[payload.index] = payload.message
    10. },
    11. },
    12. actions: {
    13. }
    14. })
    修改WebSocketConnection 类,使其接收到消息的时候调用 setMessages mutation:
    
    1. import { ref, onMounted, onUnmounted } from 'vue';
    2. import store from '@/store'
    3. class WebSocketConnection {
    4. constructor(url, index) {
    5. this.url = url;
    6. this.index = index;
    7. this.ws = new WebSocket(url);
    8. this.bindEvents();
    9. this.startSending();
    10. }
    11. bindEvents() {
    12. // ...其它代码略 看上面
    13. this.ws.onmessage = (message) => {
    14. // 当接收到数据时,将数据保存到 Vuex
    15. store.commit('setMessages', { index: this.index, message: message.data });
    16. };
    17. }
    18. // ...其它代码略 看上面
    19. }
    20. // 在 onMounted 钩子函数中创建WebSocket连接
    21. onMounted(() => {
    22. const urls = ['wss://url1', 'wss://url2', 'wss://url3', 'wss://url4', 'wss://url5', 'wss://url6', 'wss://url7', 'wss://url8', 'wss://url9', 'wss://url10'];
    23. wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
    24. });

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

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

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

    1. import { defineStore } from "pinia"
    2. export const useUsersStore = defineStore('users', {
    3. // 其它配置项
    4. state: () => {
    5. return {
    6. messages: [],
    7. };
    8. },
    9. getters: {
    10. },
    11. actions: {
    12. setMessage(payload) {
    13. this.messages[payload.index] = payload.messages
    14. }
    15. }
    16. })

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

    1. import { ref, onMounted, onUnmounted } from 'vue';
    2. import { useUsersStore } from "@/store/user.js";
    3. class WebSocketConnection {
    4. constructor(url, index) {
    5. this.url = url;
    6. this.index = index;
    7. this.ws = new WebSocket(url);
    8. this.store = useUsersStore();
    9. this.bindEvents();
    10. this.startSending();
    11. }
    12. bindEvents() {
    13. // ...同上面
    14. this.ws.onmessage = (message) => {
    15. // 收到信息后,将其存储在Pinia中
    16. this.store.setMessage({ index: this.index, message: message.data });
    17. };
    18. }
    19. // ...同上面e...
    20. }
    21. onMounted(() => {
    22. const urls = ['ws://url1', 'ws://url2', 'ws://url3', 'ws://url4', 'ws://url5',
    23. 'ws://url6', 'ws://url7', 'ws://url8', 'ws://url9', 'ws://url10'];
    24. wsConnections.value = urls.map((url, index) => new WebSocketConnection(url, index));
    25. });
    26. onUnmounted(() => {
    27. wsConnections.value.forEach(connection => {
    28. connection.stopSending();
    29. connection.ws.close();
    30. });
    31. });

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

    1. <script setup>
    2. import { computed } from 'vue'
    3. import { useUsersStore } from "@/store/user.js";
    4. const store = useUsersStore ()
    5. const message = computed(() => store.messages[0]) // 使用第一条消息
    6. script>

  • 相关阅读:
    景联文科技:提供通用多模态数据,助力AI多模态领域实现飞跃式发展
    【ArchSummit】Web3.0去中心化预言机网络技术剖析
    托尔斯泰:生活中只有两种不幸
    李炎恢ECMAScript6 / ES6+(二)
    Ngram全文检索,模糊查询解决方案
    No.8面向对象分析
    LabVIEW使用源代码控制
    基于javaweb+mysql的宿舍管理系统
    卸载Google Drive 硬盘-必须退出程序才能卸载
    Python自动化办公2.0 即将发布
  • 原文地址:https://blog.csdn.net/m0_63701303/article/details/134527311