MetinSeylan / Vue-Socket.io

😻 Socket.io implementation for Vuejs and Vuex
https://metin.sh
MIT License
3.95k stars 496 forks source link

Cannot connect multiple socket #283

Closed stevetsim closed 4 years ago

stevetsim commented 4 years ago

The old method is not working anymore https://github.com/MetinSeylan/Vue-Socket.io/pull/98

Is there any update for multiple connections?

My code:

const VueSocketIO = require('vue-socket.io')
const connectObj = {
  notification: process.env.VUE_APP_NOTIFICATION_SOCKET_SERVER_ENDPOINT,
  backend: process.env.VUE_APP_SOCKET_SERVER_ENDPOINT
}

Vue.use(
  new VueSocketIO({
    debug: true,
    connection: connectObj,
    vuex: {
      store,
      actionPrefix: 'SOCKET_',
      mutationPrefix: 'SOCKET_'
    }
  })
)
ghjacky commented 4 years ago

@stevetsim Just as below. It works for me.

import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'

const ns1 = SocketIO('http://127.0.0.1/ns1', {
  autoConnect: false,
  useConnectionNamespace: true
})
Vue.use(new VueSocketIO({
  debug: false,
  connection: ns1,
  vuex: {},
  options: {
    useConnectionNamespace: true
  }
}))

const ns2 = SocketIO('http://127.0.0.1/ns2', {
  autoConnect: false,
  useConnectionNamespace: true
})
Vue.use(new VueSocketIO({
  debug: false,
  connection: ns2,
  vuex: {},
  options: {
    useConnectionNamespace: true
  }
}))

Then, in single component which using ns1 (ns2 is the same as ns1):

  data() {
    return {
      ws_path: '/server1/socket.io'
    }
  },
  created() {
    this.$socket['ns1'].io.opts.path = this.ws_path
    this.$socket['ns1'].open()
  },
  beforeDestroy() {
    this.$socket['ns1'].close()
  }

Open and keep the connection only if you need it. Just don't forget to set the socket path before the connection opening every time.

stevetsim commented 4 years ago

@ghjacky Thanks a lot! Your approach is awesome, but I got one question. With your approach, can single component connect with two or more Namespaces at the same time? or It just allows the user to change the connection during runtime?

ghjacky commented 4 years ago

@stevetsim I made a quick test. And yes, if they have the same socket path.

stevetsim commented 4 years ago

@ghjacky Actually, I'm looking for a solution of connecting to two or more socket server(different URL) instead of multiple namespaces. However, I find a workaround already. Thanks for your help!

pedromoraisf commented 4 years ago

@stevetsim could post the solution? I'm after the same thing as you

paolodina commented 3 years ago

@stevetsim (or @pedromoraisf) sorry for bothering, I'm on the same boat could post the solution?

aepay commented 3 years ago

lt's not work for me... this.$socket['namespace'] is undefined image

ImnotLiAng commented 2 years ago

https://github.com/aripjanovsh/Vue-Socket.io This could help solve the problem

N3R00 commented 2 years ago

Não funciona para mim... this.$socket['namespace'] é indefinido imagem

i have the same problem