繁体   English   中英

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

[英]Structuring Modules and socket.io in node.js

我似乎对如何构造节点模块缺乏了解。

我在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' ...

我将如何链接/结构化文件以处理这些不同的消息,以便对套接字请求做出反应的文件不会变得太大。

基本上,如果我可以将套接字对象传递给这些模块,那就太好了。 但是问题在于,在建立连接之前,套接字是不确定的。

同样,如果我将整个io变量传递给我的模块,则每个模块都将具有io.on('connection',..)调用。 不知道这是否可能或期望。

您不需要传递整个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);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM