在node.js中构造模块和socket.io

时间:2014-07-26 10:32:02

标签: javascript node.js socket.io

我似乎不了解如何构建节点模块。

我在app.js中有以下内容。

var io = require('socket.io')(http);
io.on('connection', function(socket){

    socket.on('disconnect', function(){
        console.log('user disconnected');
    });

    console.log("New user " + socket.id);
    users.push(socket.id);
    io.sockets.emit("user_count", users.length);
});

这很好。我可以对来自客户端的各种消息做出反应,但我也有几个需要对不同消息做出反应的模块。例如,我的cardgame.js模块应该对:

作出反应
socket.on("joinTable"...
socket.on("playCard"

我的chessgame.js应该对

做出反应
socket.on("MakeAMove"...

和我的user.js文件处理:

socket.on('register' ...
socket.on('login' ...

如何链接/构造我的文件来处理这些不同的消息,以便我对socket请求作出反应的文件不会变得太大。

基本上,如果我可以将套接字对象传递给这些模块会很棒。但问题是,在建立连接之前,套接字将是未定义的。

此外,如果我将整个io变量传递给我的模块,那么每个模块都将进行io.on('connection',..)调用。不确定这是否可能。或者

1 个答案:

答案 0 :(得分:1)

你不需要传递整个io对象(但是你可以,我做以防万一我需要它)。只需将套接字传递给连接上的模块,然后为模块设置特定的on回调

主要

io.on("connection",function(socket){
    //...
    require("../someModule")(socket);
    require("../smoreModule")(socket);
});

插座

//Convenience methods to setup event callback(s) and 
//prepend socket to the argument list of callback
function apply(fn,socket,context){
    return function(){
        Array.prototype.unshift.call(arguments,socket);
        fn.apply(context,arguments);
    };
}

//Pass context if you wish the callback to have the context
//of some object, i.e. use 'this' within the callback
module.exports.setEvents = function(socket,events,context){
    for(var name in events) {
        socket.on(name,apply(events[name],socket,context));
    }
};

<强> someModule

var events = {
    someAction:function(socket,someData){

    },
    smoreAction:function(socket,smoreData){

    }
}

module.exports = function(socket){
   //other initialization code
   //...

   //setup the socket callbacks for the connected user
   require("../socket").setEvents(socket,events);
};
相关问题