I am using Vuetify together with Vuex and VueSocketIO for my WebApp and here is an example Part of the code:
Vue.use(new VueSocketIO({
reconnection: true,
debug: true,
connection: SocketIO(`http://${process.env.ip}:4000`),
vuex: {
store,
actionPrefix: 'SOCKET_',
},
}));
If I understand it correctly, using Vuex and VueSocketIO together makes it only possible to use one Socket like this at the same time.
In some cases Vue might not be able to connect to the socket specified at connection
.
I was wondering if there was a possibility to first let Vue try to connect to one socket (also with some number of reconnection attempts) but to switch to another connection
value and try with that one afterwards as a fallback?
Thank you in advance!
Final solution
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,
actionPrefix: 'SOCKET_',
},
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;
});
To specify the number of reconnection attempts you can set reconnectionAttempts option.
Example Code:
But switching to another connection is not easy as both of
vue-socket.io
andsocket.io-client
it was not designed for that.First we have to listen on reconnect_failed event which will fires when reconnection attempts is exceeded.
Then we have to create a new connection to connect to the fallback url.
The
VueSocketIO
instance have two important properties whichemitter
andlistener
we cannot create the newemitter
since it might already used in some components (with subscribe function) so we have to use old emitter but new listener.Unfortunately, we cannot import
Listener
class directly fromvue-socket.io
package. So we have to use old listener but change theio
property to the new connection then manually callregister
method.Binding
Vue.prototype.$socket
to the new connection for the future use.Example Code: