Display the number of user connections using Socket.io

I have a simple socket.io application where I can track when users connect and disconnect from my site. However, the issue is that only the first user who connects can see all current connected users, while subsequent users can only see users who join after them. I want every user who connects to be able to see the entire list of currently connected users.

Server.js

var io =  require("socket.io")(http);

var users = [];

io.on("connection", function (socket) {
console.log("User connected", socket.id);

// Need help with creating a loop to display connected users

socket.on("user_connected", function (username) {
    users[username] = socket.id;
    console.log(users);
    if (username !== 'null'){
    io.emit("user_connected", username);
    }
});

socket.on("send_message", function (data) {
    io.emit("new_message", data);
});

socket.on("user_left", function (datan) {
    io.emit("user_remove", datan);
    console.log("user left", datan);
});
});

site.html

window.onbeforeunload = function () {
io.emit("user_left", name);
};

var name =  <?php echo json_encode($_SESSION['displayname']); ?>;
var image = <?php echo json_encode($_SESSION['userpic']);?>;
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes();

io.emit("user_connected", name);

sender = name;

io.on("user_connected", function (username) {
var html = "";
html += "<li data-username='" + username + "'>" + username + "</li>";
    document.getElementById("users").innerHTML += html;
});

I tried referring to this question for guidance, but I couldn't quite grasp how 'my_room' relates to my solution. Apologies for the confusing question, I'm just feeling a bit lost in this code.

Answer №1

To share a list of users with everyone, create an object called users and update it each time a user connects. Then broadcast the updated list to all clients.

When a user disconnects, remove them from the collection before sending the disconnected user's information to other clients. This way, clients can remove the user from their own lists as needed.

If you simply need the total number of connected users, you can use io.sockets.clients().length to retrieve this information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically collapse the Shadcn-UI Accordion when the mouse exits

For my self-education project, I am working on building a sidebar with an accordion using Shadcn-ui, NextJS (13.4), React, and Node. Being new to these technologies, I have encountered a problem that I can't seem to solve. The sidebar expands on mous ...

The Signature Pad loses its focus

My HTML code is using JavaScript with Bootstrap and the Signature Pad. The issue I am facing is related to the Bootstrap Collapse feature. When I set the first panel as default, the Signature Pad does not allow me to sign. However, if I set the third panel ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

Switching up the colors of toggle arrow icons using jQuery

https://i.sstatic.net/Id0XP.png I am currently working on sorting a table and I want to use arrows to indicate which column is being sorted. I have the functionality to sort with arrows in place, but I would like to customize the color of the arrow in the ...

Tips for initiating a function for all ng-click events in AngularJS

I have created a web application using Node.js for managing mongoDB databases. The application has various click events that perform CRUD operations to alter the database's status. Each ng-click triggers a function to execute the corresponding action, ...

Is there a way to stop the dropdown from automatically appearing in a DropDownList?

Seeking a solution to use a custom table as the dropdown portion for a DropDownList in my project. My goal is for users to see the custom table when they click on the DropDownList, rather than the default dropdown menu. I expected to be able to achieve th ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

Tips for sending HTML code via query string

Currently, I am experiencing a challenge with passing HTML code using QueryString while utilizing the Ajax method to submit comments on my website. This issue arises when I write a post containing code like: "Hi everybody<br />What's up." Inst ...

Generate a unique identifier and verify its presence within an array of objects

Is there a way to generate a unique identifier and add it to an object in an array, only if the id does not already exist in any other objects within the array? Within the React code snippet provided below, the "saveColor" function was intended to accompl ...

Tips for utilizing ajax function to refresh database entries

I am working with a customer information table that is populated from a database. The last column in this table contains an edit button which, when clicked, shows a popup window with text fields pre-filled with database values. I want users to be able to u ...

Create a fixed navbar while scrolling in Angular 5

I want to make a change to the menu position so that it becomes fixed when it reaches the top of the page. Here is my approach: import { Component, OnInit, Inject, HostListener } from '@angular/core'; import {Location} from '@angular/common ...

How come my date computed property does not update reactively when changes occur?

I have a Date object in my data, and I need to convert the date into a string for a date picker component in Vuetify. The initial date is being read and displayed correctly. I am able to set the date as well - when I set a code breakpoint, I can see the ...

Is there a way to automatically scroll through a webpage?

I am looking to have a gif displayed on my website upon loading, and once the animation finishes I want the page to automatically scroll up without requiring any button clicks, revealing my main site. It is important that the gif loads automatically ever ...

Learning how to dynamically update a value in Angular based on user input

My goal is to dynamically change the output value based on user input using Angular. I have successfully implemented the functionality to increment the value, but unfortunately, when the input changes, the outputed value remains static. Below is my curren ...

Troubleshooting: Issue with detecting keypress using jQuery

Currently, I have a jQuery script that checks password strength and changes an image source based on complexity. The functionality works smoothly within jsFiddle (set to jQuery 1.91), but when implemented on my webpage, the event seems to not be triggered. ...

Can you explain the functionality of express-async-handler?

Hello, I'm trying to understand the purpose of express-async-handler. I came across it in a repository I was exploring. According to the documentation, express-async-handler is a simple middleware designed to handle exceptions within asynchronous exp ...

Activate a function when clicking on a Bootstrap toggle switch (checkbox)

Is it possible to have the function updateText() executed when I click on the checkbox with the id text_mode? I attempted using onClick="updateText()", but it didn't yield the desired outcome. While searching for solutions, I noticed that many respons ...

Solving the Angular form glitch: error message not displaying

I am facing an issue with my simple form where I am not able to display errors related to the fields. <html lang="en" ng-app="MyApp"> <head></head> <body ng-controller="AppCtrl"> <form name="myForm" id="myForm"& ...

Error encountered while establishing connection with Flutter, Node.js, and Socket.io

I'm in the process of building a multiplayer TicTacToe game using Flutter and Node.js with Socket.io integration. Here is the code: Flutter late io.Socket socket; final String url = 'http://localhost:5000'; @override void initStat ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...