Trying for days but without any luck. I installed https://www.npmjs.com/package/vue-socket.io.
I then added this code to my main.js vue file:
import VueSocketio from 'vue-socket-io';
Vue.use(VueSocketio, 'http://localhost:3001/');
My node server is running on port 3001, and when I refresh my page I do see something happen i.e. the command prompt shows a random string i.e. "PLlVISTMrfO2BzCJAAAZ". This is my connection, so that part is working!
When I want to receive a message from my server I used this code:
io.on('connection', function(socket) {
console.log('connected with id: ' + socket.id)
socket.on('SEND_MESSAGE', function(data) {
io.emit('hello_world', 'Get you right back...')
console.log(data);
});
});
When I send a message from Vue, it is received by the server, but when I try to send a message from the server to Vue it is never received.
My Vue code:
created() {
// Send a message to the server
this.$socket.emit('SEND_MESSAGE', 'Hello Node!')
// Listen
this.$options.sockets.hello_world = (data) => {
console.log(data);
console.log('something came...');
}
}
Does anyone have any idea how to fix this? I also tried this but this aint working either:
sockets: {
connect() {
// Fired when the socket connects.
console.log("server connected");
},
disconnect() {
console.log("server disconnected");
},
hello_vue: function (data) {
console.log('this method was fired by the socket server. eg: io.emit("customEmit", data)')
}
}