javascript - Keep Reference to Connected Sockets Per User -


i have (for clarity's sake) chat.

users can login, write messages, , others see [name]:[message].

i don't want send user's name , id every time write socket.emit('say', message); because that's redundant, i'm doing on server so:

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 outside of 'connection' since have tons of these in more  //complex structure , don't want create them per user connection. function dosomething(){     ...     sockets[userid].emit('foo'); // how userid @ point?     ... } 

so, how userid @ point?

notes:

  • for each user logs in , connects facebook account, client tell server save person's name , id.

i thought of doing cookie saves user's name , id, , server know user reading cookie, that's bit of ugly solution: it's redundant send information every time.

i hijack 'on' function (somehow) , add functionality know user is, because 'on' listeners must reside inside 'connection' listener anyway.

what happening user connects chat application, here

io.sockets.on('connection', function (s){   socket = s; // cache later usage 

you assign "his socket" variable socket unbound context, on own. let's second user arrives, socket gets reassigned second of second user, if savepersontosocket event socket used, same , more in detail related last user connected.

there no need keep reference s, have deal when have lot of users connecting application, solution different approach.

edit: way mapping user ids , sockets:

// assumes name of user unique var usersocket = {};  io.sockets.on('connection', function (s){   socket.on('savepersontosocket', function(user){     usersocket[user.name] = s;   } 

so saying don't want pass dosomething event payload userid? because seems valid solution me, it's not redudant, it's simplest way let server know user dealing with. other solutions might more elegant, doubt simple , maintainable one.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -