VueSocketIO提供后备连接URL

问题描述

我正在为我的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.iosocket.io-client都不是为此目的而设计的。

  • 首先,我们必须监听reconnect_failed事件,该事件将在超过重新连接尝试时触发。

  • 然后,我们必须创建一个新连接以连接到后备网址。

  • VueSocketIO实例具有两个重要属性,emitterlistener我们无法创建新的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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...