I'm trying to modularize my application and would like to emit different event to client on different js file. Sample code below shows that an event 'onlinestatus' will be fired from led.js. However I keep on getting the message 'Type Error: Cannot read property 'sockets' of undefined' whenever I try to emit the event from led.js. I suspect something could be wrong when I"m trying to export the io from /bin/www.
/bin/www
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var connectedClientsNum = 0;
io.sockets.on('connection', function(socket) {
console.log("client connected!");
socket.on('disconnect', function() {
console.log("Client disconnected...");
console.log("Total Clients Connected: " + --connectedClientsNum);
})
});
...
module.exports = server;
module.exports.io = io;
led.js
var io = require('../bin/www').io;
...
function toggleLed(leds, err, callback) {
/* toggle the led value */
if (leds[0].value == 0) {
leds[0].value = 1;
leds[0].save(function(err) {
if (err) {
err("update led error");
}
else {
var person= {"status": "online"};
io.sockets.emit('onlinestatus', person);
callback("update led from 0 to 1 success");
}
});
}
else {
leds[0].value = 0;
leds[0].save(function(err) {
if (err) {
err("update led error");
}
else {
var person= {"status": "offline"};
io.sockets.emit('onlinestatus', person);
callback("update led from 1 to 0 success");
}
});
}
}
You should check the Docs at socket.io and check to see if there is actually still a
socket.sockets.on()
function still in the socket.io framework. I'm not sure if it is still there. If you must have it working, you could try changing versions of socket.io to 0.9, which would be where I think that would work.