Get localStorage of client in node js

4

What happens is that I'm doing an application with Node js, Angular and jQuery, and with sockets, what I need is to know if the user left the application, I issued a socket which removes me from the list of connected users, the user who left, I have the following code and you are only getting it is the id of the user who first logged in, so log me in from another PC or a cell phone.

io.on('connection', function (socket) {
 console.log('Nuevo usuario conectado');
 io.emit('userconect');
 socket.on("disconnect", function () {
  io.emit('removeuser');
 });
});

y en el archivo js, tengo los sockets de esta manera:

socket.on('userconect', function () {
 var iduser = localStorage.getItem('el id del usuario');
 var userlist = $('.usersconects .users ul li[id=' + iduser + ']');
 if (userlist.length <= 0) {
  $('.usersconects .users ul').prepend('<li id="' + iduser + '"><i class="fa fa-user" aria-hidden="true"></i> Usuario prueba</li>');
  }
});
socket.on('removeuser', function () {
 var iduser = localStorage.getItem('el id del usuario');
 var userlist = $('.usersconects .users ul li[id=' + iduser + ']');
 if (userlist.length > 0) {
  userlist.remove();
 }
});

Will there be any way to obtain the user id stored from the localStorage of the client, and send it to the js file?

I appreciate your help.

    
asked by Jhonatan Rodriguez 29.09.2016 в 06:11
source

2 answers

0

What you can do is take control of the user who connects to the server, and when disconnected, send that user id to update your list, something like this:

SERVER

io.on('connection', function (socket) {
var usuarioConectado = ""; // por cada socket conectado, guardara el id


 socket.on('login',function(id){
 usuarioConectado = id;// guarda el id, y cuando se desconecte enviara este id 

 console.log('Nuevo usuario conectado:'+usuarioConectado);
 io.emit('userconect', usuarioConectado);
});

 socket.on("disconnect", function () {
  io.emit('removeuser', usuarioConectado);
 });
});

WEB

//inicia y envia el usuario al servidor, para que comunique a los demas
//clientes, que este cliente se acaba de conectar con este id
socket.emit('login',localStorage.getItem('el id del usuario'));

socket.on('userconect', function (idUsuarioConectado) {
 //agregar a tu lista local,  el nuevo usuario conectado

});
socket.on('removeuser', function (idUsuarioDesconectado) {
 //remover el usuario con id idUsuarioDesconectado
});
    
answered by 20.02.2017 / 22:42
source
0

You can add a disconnection listener and based on the id of the socket you delete the person, you have the test adding the following code and you will see that each socket is different, in this way you could do the elimination of users.

  socket.on('disconnect', (data)=>{
    console.log(socket.id);
  });
    
answered by 31.10.2016 в 00:11