导出socket.io时无法读取未定义的属性&socket;

时间:2015-04-26 08:37:32

标签: node.js socket.io

我试图模块化我的应用程序,并希望在不同的js文件上向客户端发出不同的事件。下面的示例代码显示了一个事件' onlinestatus'将从led.js.解雇但是我一直收到消息'输入错误:无法读取属性'套接字'每当我尝试从led.js发出事件时,未定义' 我怀疑当我试图从/ bin / www导出io时出现问题。

/ bin中/万维网

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 个答案:

答案 0 :(得分:-1)

您应该检查socket.io上的文档并检查socket.io框架中是否仍然存在socket.sockets.on()函数。我不确定它是否还在那里。如果你必须让它工作,你可以尝试将socket.io的版本更改为0.9,这将是我认为可行的地方。