socket io user connection added on every html page refresh?
socket.io
Solution
Refreshing the page doesn't add new connection, it basically removes current connection and creates another new connection. I think you should add a listener to disconnect event and remove the socket in the array that has been disconnected. I also don't believe that io.sockets.clients() would return 2 after refreshing as I've tested it on my machine.
If you want to track users, you need to have a user ID and store it into a key/value pair collection. Then you can restrict a user to create 2 connections by checking the collection in thr authorization handler.
var storeEachSocket = {};
io.set('authorization', function(handshake, accept){
var user = handshake.query;
if(user.id in storeEachSocket)
accept('User already connected', false);
else
accept(null, true);
});
io.on('connection', function(socket){
var user = socket.handshake.query;
storeEachSocket[user.id] = socket;
});
io.on('disconnect', function(socket){
var user = socket.handshake.query;
delete storeEachSocket[user.id]
});
Problem
I have a nodeJS application added with socket io and Express like this: Server: ``` var storeEachSocket=[]; var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { storeEachSocket.push(socket); console.log(storeEachSocket.length); var clients = io.sockets.clients(); //clients is an array console.log(clients.length); }); ``` Client: ``` <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); </script> ``` Currently there is only ONE html page served by the server. I found that, after the socket connection was built between html and server(at this time storeEachSocket.length is 1 and clients.length is 1 ),and if I refresh this html page, both storeEachSocket.length and clients.length would be 2, indicating that there are 2 socket connection between this html and the server.I want to know is this normal? the first socket connection would not die out even if after I create the second socket connection? And I also want to know, if I intend to track this user(html),what shall I do if there are two socket connections used by the one user?