2015-10-01 27 views
11

我正在尝试为我的节点服务器上的每个事件记录event nameparameter。为此我用如何在socket.io的中间件中获取事件详细信息

io.use(function(socket, next){ 
    // how to get event name out of socket. 
}); 

现在,我试图获取事件名称和参数时卡住了。对我来说,它看起来像来自API开发者的常见需求,所以我非常肯定,必须有一些方法来图书馆来获取,我试图阅读文档和来源,但我无法得到的东西。

+0

您是否尝试过使用['util.inspect'](https://nodejs.org/api/util.html#util_util_inspect_object_options)来打印'socket'的属性,以查看是否有一个包含您需要的数据的属性?这可能有点工作,但如果它不在文档中,找到合适的属性是最好的方法。 – Wouter

+0

我试图检查'socket.request',但没有检查过套接字本身。 – guptakvgaurav

+0

我也想知道这一点。我使用[recursive-iterator](https://github.com/nervgh/recursive-iterator)以递归方式遍历'socket'对象中的所有属性,但无法找到该事件的字符串'“connection”'。在socket.io源代码中有一个'ondecoded',它用ID /消息调用'onpacket'。并且'使用'中间件似乎没有涉及任何(实际上它似乎发生在所有这一切之前),所以这可能是为什么这个细节在这里不可用。真的很感激,如果有人可以提供一个更权威的答案,虽然.. – laggingreflex

回答

2

套接字事件需要正确处理,在任何情况下如果事件没有处理,就不会有响应。

var io = require('socket.io')(server); 
var sessionMiddleWare=(session({secret: 'secret key', resave: true, saveUninitialized: true,cookie: { path: '/', httpOnly: true, maxAge: 300000 },rolling: true})); 

app.use(sessionMiddleWare) 

io.use(function(socket, next) { 
    sessionMiddleWare(socket.request, socket.request.res, next); 
}); 

io.on('connection', function(socket) { // On Socket connection. 
    // inside this you can use different events 

    //event name and parameters can be found in socket variable. 

    console.log(socket.id) // prints the id sent from the client. 
    console.log(socket.data) // prints the data sent from the client. 

    // example event 

    socket.on('subscribe', function(room) { // Event sample. 
     console.log('joining room', room); 
     socket.room=room; 
     socket.join(room); 
    }); 
}) 

希望这会有所帮助。

相关问题