可复制现成代码直接使用!!
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>