javascript - set username in socket io connection -
i have chat application have handle online users. how can send user name in:
var myiosocket = io.connect();
so can make list @ backend.
currently doing this.
socket.on("connect",function(){ notification.primary('connected'); socket.emit('iamonline',{ username: $rootscope.username }); });
backend :
var onlineusers = {}; io.sockets.on('connection', function(socket){ socket.on('iamonline',function (data) { console.log(data.username," connected.") onlineusers[data.username] = socket; users[data.username] = socket; currentuser = data.username; console.log(socket) io.sockets.emit("liveusers",object.keys(onlineusers)); }); socket.on('disconnect', function(){ delete onlineusers[currentuser]; console.log(currentuser," disconnected."); io.sockets.emit("liveusers",object.keys(onlineusers)); }); });
i had same issue different project , found out best way query , value on handshake.
server.js
io.on('connection' , function(socket){ if(typeof socket.handshake.name!="undefined"){ user = { name : socket.handshake.query.name, id : socket.handshake.query.id, email : socket.handshake.query.email, } } });
on client side,
if(typeof io != "undefined"){ var visitor = io.connect('ws://127.0.0.1:8000' , { 'query': $.param({token: '<?=session::$instance->session['id']?>'}) + '&name=<?=session::get("username")?>&id=<?=session::get("id")?>&email=<?=sesion::get("email")?>' }); }
Comments
Post a Comment