S
I’ve made a bare NodeJs backend and setup a global variable for devices storage. That added a socket.io file that periodically sends a device.
On the Quasar frontend, I’ve added a boot file and setup one page for receiving the data. But I can’t find why it doesn’t receive anything, and the backend doesn’t inform about client’s connection. Perhaps you can give me a hand:
Backend:
// socket.js
const config = require('./config');
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
console.log('socket: module loaded'); //This is shown
app.get('/', (req, res) => {
res.status(200).send('This is the backend server.'); //This works
});
function sendDevice(id) {
const device = devices.find((i) => i.id === id);
io.emit('device', device);
}
function updateDevice(id, data) {
var device = devices.find((i) => i.id === id);
if (!device) devices.push(data);
else device = data;
pendingCommit = true;
}
http.listen(config.socketPort, () => {
console.log('socket: websocket listening on *:' + config.socketPort); //This works
});
// All of this doesn't seem to work
io.on('connection', (socket) => {
console.log(`socket: client connected with id: ${socket.id}`);
socket.on('updateDevice', function(data) {
if (!data.id) {
console.error('socket: [ERROR] Received a device update request without a correct id.');
return;
}
updateDevice(data.id, data);
});
setInterval(function() {
sendDevice('1');
}, 5000);
io.on('disconnect', () => {
console.log(`socket: client disconnected with id: ${socket.id}`);
});
});
module.exports = {
sendDevice
};
Frontend:
// boot/socket.js
import io from 'socket.io-client'
const socket = io.connect('http://localhost:3002')
export default ({ Vue }) => {
Vue.prototype.$socket = socket
}
export { socket }
<!-- pages/info.vue -->
<template>
<q-page padding class="window-height window-width row justify-center">
Selected: {{selected}}<br/> <!-- Shows the correct Id -->
Name: {{device.display_name}} <!-- Shows default -->
<q-knob
readonly
v-model="device.battery_level"
show-value
size="150px"
:thickness="0.22"
color="green"
track-color="green-2"
class="q-ma-md"
>
{{ device.battery_level }}%
</q-knob>
</q-page>
</template>
<script>
export default {
name: 'Info',
data () {
return {
selected: '',
settings: [],
device: {
id: '',
display_name: 'Empty',
battery_level: '-1'
}
}
},
mounted () {
this.selected = this.$q.localStorage.getItem('selectedItem')
this.$socket.on('device', (data) => {
this.device = [...this.device, data]
})
}
}
</script>