S
S
StuGGs2014-07-04 22:10:31
Node.js
StuGGs, 2014-07-04 22:10:31

User + socket.io, how to connect the same user in different browser tabs?

Hello!
When opening a new tab in the browser, a new connection is created to the sulfur part of the chat on socket.io. There was such a question. If every time a new browser window is opened, a new connection is established with a unique socket identifier - socket.id, then how to implement it so that after authorization, if the user has opened several tabs, his own nickname is shown?
Those. user connected in one tab. On the server, its login is stored in an array. The user opens a second tab, the cookies are already set in the previous one. But, it turns out that one user corresponds to several socket.id or is this normal?
1 - connection --- Vasa - socket.id = fgkjdfhsjg
2 - connection --- Vasa - socket.id = safjdlksad
Or, is it possible to somehow implement the connection of one client in a different way so as not to break the connection in the previous tab?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
globalmac, 2014-09-02
@StuGGs

Socket.io indeed generates a unique handshake for each connection, and this is correct and in the order of things.
If you are interested in displaying users online in the list on the site, for example, then you can solve the problem using the callback () function.
We will pass the user_id to the signaler server, for example via PHP, and then check if this user_id is in the array of connected users.
server.js example:

userlist = {}; // Массив юзеров
io.sockets.on('connection', function(socket) {
  socket.on('connect', function(data, callback) {
    socket.user_id = data.user_id; // в user_id передаём идентификатор пользователя
    if(socket.user_id in userlist) {
        callback(false); // Ага, этот юзер уже открыл вкладку, значит ничего не делаем
    } else {
        callback(true); // А вот тут он новенький
        userlist[socket.user_id] = data; // Фигачим его в массив
        UpdateUserList(); // Обновляем список онлайн юзеров
    } 
  });
        // При дисконнекте
        socket.on('disconnect', function() {
             delete userlist[socket.user_id];
             // Тут немного магии, чтобы юзеры в списке онлайн на клиенте не моргали, когда например они ходят по ссылкам сайта
             setTimeout(function () {
                 UpdateUserList();
             }, 1000);
        });
    
        function UpdateUserList() {
    io.sockets.emit('updateusers', userlist);
  }
});

B
Burgul, 2014-07-05
@Burgul

But, it turns out that one user corresponds to several socket.id or is this normal?

This is fine. socket.io in any case, you need to name each connection uniquely so that you can work with it separately, regardless of whether there is such a login in your array or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question