ItsMyLife
ItsMyLife

Reputation: 478

Open socket connection in component

Following official doc vue-socketio i init socket in store.js.

import VueSocketio from 'vue-socket.io'
import socketio from 'socket.io-client'
Vue.use(VueSocketio, socketio(process.env.SOCKET_PATH), store)

But socket opens right after project is openned. Can i avoid this string Vue.use(VueSocketio, socketio(ws://somepath), store) and use something like this this.$socket.connect(ws://somepath) in my component. And how i ca open two different socket connection from 1 client?

Upvotes: 1

Views: 1081

Answers (1)

Alex Freshmann
Alex Freshmann

Reputation: 481

You can use html5 WebSocket. And you don't need to import or require it. It's already provided. You can open any number of connections. In your component's script:

...
data() {
  return {
    ws1:  null,
    ws2:  null,
  }
},
mounted() {
  this.startStream1()
  this.startStream2()
},
methods: {
  startStream1 () {
    let vm           = this
    vm.ws1           = new WebSocket("wss://somepath1")
    vm.ws1.onmessage = function (event) {
      vm.$store.dispatch("handleStream", JSON.parse(event.data))

    }
    vm.ws1.onerror   = function (error) {
      console.log(error)
    }
  },
  closeStream1 () {
    this.ws1 && this.ws1.close()
  },
  startStream2() {
    let vm          = this
    vm.ws2          = new WebSocket("wss://somepath2")
    ...
  },
  ...
}

Upvotes: 1

Related Questions