2014-05-14 40 views
13

例如我的想法是:Socket.io - 聽在不同的文件事件的node.js

File1.js

io.sockets.on('connection', function (socket) { 
     socket.on('file1Event', function() { 
      //logic 
     }); 
}); 

File2.js

io.sockets.on('connection', function (socket) { 
     socket.on('file2Event', function() { 
      //logic 
     }); 
}); 

此代碼它是一個節點服務器,我會有這個代碼的問題嗎?

回答

25

不,只是使用相同的「io」對象。

File1.js

exports = module.exports = function(io){ 
    io.sockets.on('connection', function (socket) { 
    socket.on('file1Event', function() { 
     console.log('file1Event triggered'); 
    }); 
    }); 
} 

File2.js

exports = module.exports = function(io){ 
    io.sockets.on('connection', function (socket) { 
    socket.on('file2Event', function() { 
     console.log('file2Event triggered'); 
    }); 
    }); 
} 

app.js

var app = require('http').createServer(handler) 
    , io = require('socket.io').listen(app) 
    , fs = require('fs') 
    , file1 = require('./File1')(io) 
    , file2 = require('./File2')(io) 

app.listen(3000); 

function handler (req, res) { 
    fs.readFile(__dirname + '/index.html', 
    function (err, data) { 
    if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'); 
    } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

的index.html

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var socket = io.connect('http://localhost'); 
    socket.emit('file1Event'); // 'file1Event triggered' will be shown 
    socket.emit('file2Event'); // 'file2Event triggered' will be shown 
</script>