Skip to content

Instantly share code, notes, and snippets.

@nmeylan
Created August 24, 2017 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmeylan/ee3f85346aa75907558b8cff9e3ef328 to your computer and use it in GitHub Desktop.
Save nmeylan/ee3f85346aa75907558b8cff9e3ef328 to your computer and use it in GitHub Desktop.
Auto reconnect websocket
import VueWS from 'vue-native-websocket'
import Observer from 'vue-native-websocket/src/Observer'
import App from './App'
import store from './store'
const wsOptions = {store: store, format: 'json'}
Vue.use(VueWS, "myWsEndpoint", wsOptions)
new Vue({
el: '#app',
store,
template: '<App/>',
components: {App},
created () {
this.unsubscribe = this.$store.subscribe((mutation, state) => {
if (mutation.type === 'SOCKET_ONCLOSE' ||
// On error and while not reconnecting (state managed in my store)
(mutation.type === 'SOCKET_ONERROR' && !state.websocket.socket.isConnected && !state.websocket.socket.isReconnecting)) {
this.reconnectWebSocket()
}
})
},
methods: {
reconnectWebSocket () {
setTimeout(() => {
this.$store.commit('SOCKET_ONRECONNECTING', this.$socket)
this.$socket = new Observer(wsEndpoint, wsOptions)
this.$socket.onopen = () => {
this.$store.commit('SOCKET_ONOPEN', this.$socket)
}
}, 2000)
}
},
beforeDestroy () {
this.unsubscribe.call()
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment