0

I am making a simple chat, so when someone logs on I have this:

socket.broadcast.emit('logon', { socketID: socket.id, username: username }); 

So if I login via chrome as "Bob", and then I log in via Edge as "Ted", I will see "Ted" when "Ted" logs in and I am looking at the chat with chrome.

But how do I get the list of current clients with usernames as soon as I log in?

So if "Ted" is already there, and I log in as "Bob" from a different browser, I want to see "Ted" in the list.

Is it possible to do without using a database to store each user that logs in, as that is the only way I can think of but would prefer not to use a database?

1 Answer 1

1

There is no need to use a database. The only thing you must have is an array of users that is connected to certain event listeners server side. Example:

var users = []; // Array of users online io.on('connection', function(socket) { var user = { // On connection, create an object for the user. socket: socket, username: null } socket.on("login",function(data) { // When the user logs in, set his username and add him to the users array. user.username = data.username; users.push(user); }); socket.on("disconnect",function() { // When user disconnects, remove the object from the array. var index = users.indexOf(user); if (index !== -1) users.splice(index); }); }); 

As you can see, there is now an array of all online users that you can access.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.