保持对每个用户的连接套接字的引用

vsy*_*ync 7 javascript node.js socket.io

我有一个(为了清楚起见)聊天.

用户可以登录,编写消息,其他人可以看到[name]:[message].

我不希望每次写入时都发送用户的名称和ID,socket.emit('say', message);因为这是多余的,所以我在服务器上做的是这样的:

var io = require("socket.io").listen(server),
    sockets = {};

io.sockets.on('connection', function (socket){
    socket.on('savePersonToSocket', function(user){
        socket.user = user;
        sockets[user.id] = socket;
    }
    socket.on('doSomething', doSomething);
});

// must be outside of 'connection' since I have TONS of these in a much more 
//complex structure and I don't want to create them all per user connection.
function doSomething(){
    ...
    sockets[userID].emit('foo'); // how to get the userID at this point?
    ...
}
Run Code Online (Sandbox Code Playgroud)

那么,我如何在那时获得userID?

笔记:

  • 对于登录并与其Facebook帐户连接的每个用户,客户端将告诉服务器保存该人的姓名和ID.

我想用一个保存用户名和ID的cookie来做这件事,服务器会通过读取cookie知道它是哪个用户,但这有点难看:每次发送这些信息都是多余的.

我还可以劫持'on'函数(以某种方式)并添加将知道它是哪个用户的功能,因为所有'on'侦听器无论如何都必须驻留在'connection'侦听器中.

vsy*_*ync 1

从理论上讲,像这样丑陋的东西应该可以工作,但是恕我直言,使用apply是很糟糕的,并且缺乏简单的函数指针使得代码更丑陋

var io = require("socket.io").listen(server);

io.sockets.on('connection', function (socket){
    socket.on('savePersonToSocket', function(user){
        socket.user = usr;
    }

    // No more simple function pointers....
    socket.on('doSomething', function(){
       // pass the Socket as the scope
       doSomething.apply(socket, arguments);
    });

});

function doSomething(){
    ...
    this.emit('foo');
    ...
}
Run Code Online (Sandbox Code Playgroud)