Refreshing the page allows Socket.io to establish multiple connections

I've been working on setting up a chatroom, but I've noticed that each time the page refreshes, more connections are being established. It's interesting because initially only one connection is created when I visit the chat room page. However, after just one refresh, two clients are connected. And with each subsequent refresh, an additional connection is added.

Here is the code for my chat route:

    /* GET home page. */
router.get('/', accessControl.ensureAuthenticated, function(req, res, next) {
  const io = req.app.io;
  console.log('const io created');
  io.on('connection', function(socket){
    console.log(' %s sockets connected', io.engine.clientsCount);
    console.log('[NodeApp] (socket.io) A client has connected');
    socket.on('chat message', function(message){
      if (message.sessionID == req.session.id) {
        io.emit('chat message', message);
        console.log('message: ' + message.message);
      } else {
        console.log('client sessionID ('+message.sessionID+') does not match server sessionID ('+req.session.id+')');
      }
    });
    socket.on('disconnect', function(){
      console.log('[NodeApp] (socket.io) A client has disconnected');
      socket.disconnect();
    });
  });

  res.render('chat/index', {
    title: "Chat",
    //send session id for client verification
    sessionID: req.session.id,
  });
});

When the chat page is refreshed three times, here is the output:

const io created
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
const io created
[NodeApp] (socket.io) A client has disconnected
[NodeApp] (socket.io) A client has disconnected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
1 sockets connected
[NodeApp] (socket.io) A client has connected
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)
message: test message (should be sent 3 times)

Answer №1

Putting the following code snippet:

io.on('connection', function(socket){...}

within a route handler is not recommended. Each time the route is accessed, a new listener for the event is created, leading to an accumulation of duplicate listeners. As a result, messages can be processed multiple times by these redundant event handlers.

To avoid this issue, it is crucial to place the code outside any route handler. Configuration of the socket.io server and its listeners should be done during the setup of the socket.io server itself, rather than within a route handler.

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

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

Showcasing a Collection of Dropdown Options for All Angular Material Icons in Angular Versions 2 and Above

I'm currently developing an Angular 10 application that utilizes Angular Material Icons. I am in search of a method to dynamically showcase a dropdown menu containing all the available Material Icons. My attempt to programmatically retrieve the icon ...

What is the process for converting strings or text to EBCDIC using JavaScript?

In the midst of developing a website, I am working on a feature that allows users to input a minimum of 256 characters/strings (with code verification), choose between ASCII or EBCDIC conversion, and view the converted text string displayed on the page bas ...

"Exploring the Possibilities with WordPress and Waypoint Js

After exploring various resources and tutorials online, I am struggling to implement Waypoints with WordPress. Despite placing the necessary files like waypoints.min.js and waypoints.js in the designated download folder within the js directory of my templa ...

Error message: "The term 'Outlet' is not recognized in react-router version 6.4"

What is the proper way to define the Outlet component in react-router version 6.4? Below is a code snippet: function Layout() { return ( <div> <Navbar /> <Outlet /> <Footer /> </div> ); } ...

Tips for changing the state of a parent DOM element from a child component several levels deep in a React application

I am currently incorporating both react-router-dom and Material-UI into my application. Below is a basic example I have created using the following files: routes.tsx import { Outlet, createBrowserRouter } from "react-router-dom" const App = () ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it' ...

Is the HTML Page loading before the AJAX call is made?

On my HTML Page, I have a button tag that looks like this: <button ng-hide="alreadyFreinds()" type="button" class="btn btn-primary btn-lg">Friend</button> However, when attempting to access certain parts of the alreadyFriends function shown b ...

When the key code is equal to "enter" (13), the form will be submitted

When I press the Enter key, I want to submit a form if there are no error messages present. Here is the function I have created: $(targetFormID).submit(function (e) { var errorMessage = getErrorMessage(targetDiv); if (e.keyCode == 13 && errorMessa ...

Monitoring Changes in an Array of Objects with Angular's $watch Feature

Imagine having an array of animal objects linked to the scope. Each object contains a 'name' field and a 'sound' field. After that, I set up a $watch on the array with the objectEquality flag set to true (the third argument). Then, in ...

Create a repeating function that will show an image based on the specific class assigned to each individual element

Can someone help me create a function that automatically applies to all divs with a specific class on my document? I want the function to check for the presence of another class within those divs and display an image accordingly. document.getElementsByCla ...

What are the advantages of choosing Express over AngularJS?

It's clear to me that Express is typically found on the server, while Angular is usually on the client side. However, from what I've gathered, Angular has the capability to perform all the functions that Express can, such as: routing interactin ...

Encountering a "Module not found" issue while attempting to utilize the Google APIs Node.js client

Attempting to incorporate the Google API Node.js client into a fresh React Web application. Here is my package.json: { "name": "onboarding", "version": "0.1.0", "private": true, "devDependencies": { "react-scripts": "0.8.4" }, "dependencie ...

What are the steps to successfully implement "Pointermove" event delegation in Safari iOS for parent/child elements?

I've encountered an issue that I'm struggling to find a solution for. My goal is to implement an event delegate using pointermove on a parent container, and I need to be able to detect when the event transitions between a child element and the pa ...

Setting field names and values dynamically in MongoDB can be achieved by using variables to dynamically build the update query

I am working on a website where users can place ads, but since the ads can vary greatly in content, I need to be able to set the field name and field value based on user input. To achieve this, I am considering creating an array inside each document to sto ...

Automated Menu Selection using Selenium

I'm currently facing a challenge in writing a Python script using Selenium to interact with a webpage. I am struggling to use the .click() method to select an expandable list on the page. Despite successfully logging in and navigating to the desired p ...

Troubleshooting: Why is Jquery unable to retrieve image height?

Having trouble using jQuery to find the actual height of the first image nested within a container. I can access the src attribute but not the height. Any suggestions on how to get the accurate height? Is it necessary to retrieve heights via CSS? Unfortu ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

preserve functionality when switching between pages

I have created two simple functions that can change the background color of the body. <script type="text/javascript"> function switchBackground(color){ document.body.bgColor=color; } </script> I am using links with onclick to execute thes ...