6

I am building a website with a node.js server.

How would i track logged-in users (clients) and store their id's on the node.js server?

3 Answers 3

7

Try this:

var http=require('http');

var connected_users={};

var server=http.createServer(function(req,res){
    res.end('hi');
});

server.on('connection',function(socket){
    socket.__fd=socket.fd;
    connected_users[socket.__fd]=socket.remoteAddress;
    console.log(connected_users);
    socket.on('close',function(){
        delete connected_users[socket.__fd];
        console.log(connected_users);
    }); 
});
server.listen(8080);

It prints out to console the array of connected users every time someone connects/disconnects

Sign up to request clarification or add additional context in comments.

Comments

0

You can use connect or express NPM modules (express is an extension of connect). Connect (and thus express) has support for cookie-based sessions. Express is a very lightweight and popular framework.

To store users persistently, you can use 'dirty' module. If you need a more advanced store - you can use MongoDB, Riak or even plain old SQL databases (postgreSQL and mySQL), however I suggest to start with dirty or riak to learn the modern approach (namely, key-value stores, in-memory databases, horizontal scalability, document-oriented and other noSQL databases).

3 Comments

The thing is i want to store a random id for a new connected client in an array and when they disconnect that this id wil be removed from that array.
HTTP is connectionless protocol. So you cannot track when a user disconnects. The code above is useless as most users will disconnect immediately after the connection.
Is there a way that this will be possible??
0

If you use express then you should set a session middleware app.use(express.cookieParser()) and app.use(express.session({secret:'some secret'}). By default it stores in memory but you able to use database to store sessions. For more details look in express guide. Is it it?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.