在node.js中构造模块和socket.io
问题描述:
我似乎缺乏对如何构造节点模块的理解。我有以下app.js
。在node.js中构造模块和socket.io
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);
};
这看起来像我想要的。如何处理模块,但需要多个套接字?我假设先创建对象,然后简单地使用addSocket函数。 –