Cannot read property 'socket's of undefined when exporting socket.io

你说的曾经没有我的故事 提交于 2019-12-24 10:46:53

问题


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");
            }
        });
    }       
}

回答1:


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.



来源:https://stackoverflow.com/questions/29875470/cannot-read-property-sockets-of-undefined-when-exporting-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!