Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Vue.js with vue-socket-io

I am trying to use vue-socket-io with Vue.

I can emit messages from client to server without a problem. But, from server to Vue app, I can't receive anything.

What am I doing wrong?

main.js:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";

// socket io
import * as io from "socket.io-client";
import VueSocketIO from "vue-socket.io";

Vue.use(
  new VueSocketIO({
    debug: true,
    connection: io('http://localhost:3000'), // options object is Optional
  })
);

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  vuetify,
  render: (h) => h(App),
}).$mount("#app");

App.vue:

<template>
  <v-app>
    <div>Test</div>
  </v-app>
</template>

<script>
export default {
  name: "App",
  mounted() {
    this.$socket.on("user-connected", (data) => {
      debugger;
      console.log(data);
      this.$socket.emit("users");
    });
    this.$socket.emit("users");
    this.$socket.on("users", (data) => {
      console.log("users", data);
    });
};
</script>

Node server:

...
const server = http.createServer(app);
const io = require("socket.io")(server);
server.listen(port);
server.on("listening", () => {
  const addr = server.address();
  console.log(`Mágica acontecendo em  ${addr.address} na porta ${addr.port}`);
});

io.on("connection", async function (socket) {
    console.log("conectado:" + socket.id);
    socket.broadcast.emit("user-connected", socket.id);
});
  
like image 650
Luiz Alves Avatar asked Jun 21 '20 22:06

Luiz Alves


People also ask

Is there a socket Io plugin for Vue?

There is no lack of socket.io plugins for Vue. vue-socket.io looks like a good solution. However, I try to avoid 3rd party dependencies if I can easily implement their function myself, as in the case of socket.io. To reuse the socket I need to pass the same instance to Vue and the Vuex store.

How do I bind to a socket event in Vue?

First, enable the vue-socket.io plugin in your app startup file: import Vue from 'vue'; import socketio from 'socket.io'; import VueSocketIO from 'vue-socket.io'; export const SocketInstance = socketio('http://localhost:4113'); Vue.use(VueSocketIO, SocketInstance) ... Now, we can bind to socket events directly in our components:

What is Vue-socket?

Vue-Socket.io is a socket.io integration for Vuejs, easy to use, supporting Vuex and component level socket consumer managements When you set store parameter in installation, Vue-Socket.io will start sending events to Vuex store.

How do I run a Vue app on a node server?

When you’re done bootstrapping your Vue application, change into the new Vue application directory and start the development server. This will serve your Vue application on localhost:8080. You can navigate to it on your browser and you should see your Vue application running. Next, let’s set up our custom Node server.


2 Answers

Using socket.io with Vue.js and Node.js full example:

In your backend (Node.js):

//setting up sockets
const app = express()
const server = http.createServer(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
  socket.on('sendUpdateUsers', function(data) {
    io.emit('usersUpdate', data)
  });
})

Sending a socket update from the component:

import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  users: []
 }
},
methods: {
 this.socket.emit('sendUpdateUsers', {users: this.users})
}

Listening to socket in the component:

import io from 'socket.io-client';

data() {
 return {
  socket: io(),
  users: []
 }
},
created() {
  this.socket.on('usersUpdate', (data) => {
   this.users = data.users
  })
}
like image 51
Jakub A Suplicki Avatar answered Sep 23 '22 02:09

Jakub A Suplicki


I had this issue earlier and fixed it with listener.subscribe:

mounted() {
    this.sockets.listener.subscribe("user-connected", (data) => {
        debugger;
        console.log(data);
        this.$socket.emit("users");
    });
    this.$socket.emit("users");
    this.sockets.listener.subscribe("users", (data) => {
        console.log("users", data);
    });
},

Not sure if it'll work for you but it's worth a try.

like image 35
Daniel_Knights Avatar answered Sep 24 '22 02:09

Daniel_Knights