问题描述
我正在为我的WebApp使用Vuetify以及Vuex和VueSocketIO,下面是示例代码部分:
Vue.use(new VueSocketIO({
reconnection: true,debug: true,connection: SocketIO(`http://${process.env.ip}:4000`),vuex: {
store,actionPrefix: 'SOCKET_',},}));
如果我理解正确,那么一起使用Vuex和VueSocketIO只能同时使用一个这样的Socket。
在某些情况下,Vue可能无法连接到connection
指定的套接字。
我想知道是否有可能先让Vue尝试连接到一个套接字(也进行多次重新连接尝试),然后切换到另一个connection
值,然后再尝试使用那个作为后备? >
提前谢谢!
最终解决方案
const options = {
reconnection: true,reconnectionAttempts: 2,reconnectionDelay: 10,reconnectionDelayMax: 1,timeout: 300,};
let connection = new SocketIO(`http://${process.env.ip}:4000`,options);
const instance = new VueSocketIO({
debug: true,connection,vuex: {
store,options,});
const options2 = {
reconnection: true,reconnectionAttempts: 4,};
connection.on('reconnect_Failed',() => {
connection = new SocketIO(`http://${process.env.fallback}:4000`,options2);
instance.listener.io = connection;
instance.listener.register();
Vue.prototype.$socket = connection;
});
解决方法
要指定重新连接尝试的次数,可以设置reconnectionAttempts选项。
示例代码:
const url = `http://${process.env.ip}:4000`
const options = {
reconnectionAttempts: 3
}
Vue.use(new VueSocketIO({
debug: true,connection: new SocketIO(url,options),vuex: { ... }
}))
但是切换到另一个连接并不容易,因为vue-socket.io
和socket.io-client
都不是为此目的而设计的。
-
首先,我们必须监听reconnect_failed事件,该事件将在超过重新连接尝试时触发。
-
然后,我们必须创建一个新连接以连接到后备网址。
-
VueSocketIO
实例具有两个重要属性,emitter
和listener
我们无法创建新的emitter
,因为它可能已经在某些组件中使用了(带有订阅函数),所以我们必须使用旧的发射器,但要使用新的侦听器。 -
很遗憾,我们不能直接从
Listener
包中导入vue-socket.io
类。因此,我们必须使用旧的侦听器,但是将io
属性更改为新的连接,然后手动调用register
方法。 -
将
Vue.prototype.$socket
绑定到新连接以供将来使用。
示例代码:
const url = `http://${process.env.ip}:4000`
const fallbackUrl = `http://${process.env.ip}:4001`
const options = {
reconnectionAttempts: 3
}
const connection = new SocketIO(url,options)
const instance = new VueSocketIO({
debug: true,connection,vuex: {
store,actionPrefix: 'SOCKET_'
},options
})
connection.on('reconnect_failed',error => {
const connection = new SocketIO(fallbackUrl,options)
instance.listener.io = connection
instance.listener.register()
Vue.prototype.$socket = connection;
})
Vue.use(instance)