L
L
lgick2014-04-26 09:37:33
Node.js
lgick, 2014-04-26 09:37:33

Is it possible to make such a connection (socket.io)?

Before connecting via socket.io, authorization occurs. At this point, you can either accept the connection or cancel it.
I want to do a check on the user's ip and in the case of an existing connection on this ip, transfer the existing object to a new connection, and close the old one.
Example: a user on tab A enters a website, a ws connection is opened and information flows through it. Then the user in tab B visits the same site. Instead of creating a new ws connection, information from tab A begins to flow to tab B, while A closes.
Perhaps so?
I think, if possible, it should be done in this function:

io.set('authorization', function (handshakeData, callback) {
      // проверка по ip и настройка соединения
  });

I didn't try, I didn't succeed

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Shurygin, 2014-04-26
@duderu

What's difficult? Store the user's IP and the socket ID or key that you have there to identify socket connections.
If the client fell off - we throw it out of this array, if it is hooked - we replace the old hash key with a new one (new tab).
When connecting, some kind of authorization function must be called, which will say "ok / no". Well, you just need to insert into each handler a check of the current connection identifier for the presence in the active array - if it is not there, we call the client method, in the handler of which we close the socket connection to the server and that's it.

A
Alexey Lizurchik, 2014-05-17
@likerRr

Do you absolutely need the user to be disconnected if he opens a new tab?
Basically, you are doing everything right. But I would recommend making sessions not an object, but an array where session objects will be stored. Based on this, you get something like this:
Include the underscore module at the beginning of the file (underscore.js library ) Next
, write inio.sockets.on('connection')

// массив сессий
var sessions = [],
      ip = ?; // ваша реализация

// проверяем, имеется ли уже активная сессия
var found = (_.find(sessions, function(session) {
     return session.ip === ip;
}));

// обновляем (не удаляем!) сессию, если нашли, сказав предыдущей вкладке "пока-пока"
if (found) {
      found.socket.emit('bye_bye', 'You are disconnected from server');
      found.socket.disconnect();
      found.socket = socket;
      found.ip = ip;
}
else {
      // добавляем сессию
      sessions.push({
             socket: socket,
             ip: ip
      });
}

All this is written in connection, because. you are autzorizathionnot yet connected to the socket.
PS The code is just an unoptimized and untested prototype

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question