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

A quirky bug with Tumblr's JS/Jquery Infinite Scroll and Masonry feature

As someone new to JS/JQuery and masonry, I seem to be facing a puzzling issue with overlapping posts/divs. Despite my extensive search for answers, I have run out of ideas. The problem arises from the content at this link: Below is the complete theme cod ...

Is it possible to navigate to the Next page using a different button instead of the pagination controls

Is it possible to navigate to the next page upon clicking a button labeled "Press me"? Here is the code snippet: <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/an ...

What is the best way to transfer this module's information to index.ejs using Express?

Having some difficulties with my first simple app. The core functionality is working fine: the scrape.scrape() function uses a module to retrieve an array of strings (by scraping data from an external site). When I execute 'node index.js', I can ...

Having trouble with the HTML5 canvas for loop not rendering the initial object in the array?

Essentially, I'm attempting to iterate through each letter in a text string (specifically the text "marius"). However, there's an issue where the first letter is not being displayed. When the text is "marius", only "arius" is drawn. I've exh ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

NodeJS produces identical outcomes for distinct requests

RESOLVED THANKS TO @Patrick Evans I am currently working on a personal web project and could use some assistance. In my website, users are prompted to upload a photo of their face. When the user clicks the "upload" button, the photo is sent with a request ...

Is the sequence of routes significant in the Express framework?

Currently, I am in the process of creating a straightforward CMS with Restfull routes using Express.js. Initially, everything was running smoothly. However, when I attempted to make some adjustments to tidy up my routes, specifically by rearranging the rou ...

Encountering NPM Abortion Issue in Node.js

I am a beginner in node.js and have successfully installed it. However, when I try to initialize npm, I encounter an error that causes it to abort. My system has high memory capacity with 32GB RAM and 1TB HD. Although the 'npm -v' command works ...

Incorporate javascript into your XML transformations with XSLT

I need help with inserting JavaScript in XSLT. Here is an example of what I am trying to do: <xsl:variable name="comboname" select="@name" /> <script type="text/javascript"> var z{$comboname} = {$comboname}; </scri ...

Navigating to a form within an Angular-UI uib-tab

Is it possible to access a form within a uib-tab for validation purposes? To see an example, check out this plunker: http://plnkr.co/edit/8hTccl5HAMJwUcHEtnLq?p=preview While trying to access $scope.forminside, I found that it's undefined (referring ...

Exploring new classes with jQuery's .not() and :not()?

I am working on a memory game where I need to flip cards and check if two are equal. My issue is that I do not want the function to run when clicking on a card that is already flipped, or on another flipped card. I tried using jQuery's .not() and :no ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...

Refresh the Dom following an Ajax request (issue with .on input not functioning)

I have multiple text inputs that are generated dynamically via a MySQL query. On the bottom of my page, I have some Javascript code that needed to be triggered using window.load instead of document.ready because the latter was not functioning properly. & ...

MERN stack tutorial: How to modify a particular string in an array's object

When it comes to connecting my backend (Express) server to the database using mongoose, I am facing an issue with performing CRUD operations. While I can easily access and update direct data in objects, I need a solution to manipulate array data as well. ...

Exploring the TLS configuration for a Node.js FTP server project: ftp-srv package

I'm seeking to comprehend the accurate setup of TLS for my FTP project (typescript, nodejs) using this API: ftp-srv The documentation provided is quite basic. In one of the related github issues of the project, the author references his source code / ...

The useEffect hook fails to recognize changes in dependencies when using an object type obtained from useContext

Utilizing the useContext hook to handle theme management in my project. This is how the ThemeContext.js file appears: "use client"; import { createContext, useState } from "react"; let themes = { 1: { // Dark Theme Values ...

How do I iterate through my state in React Redux?

Currently, I am delving into Redux by creating a to-do list in React. I have been pondering on the utilization of the map function to iterate over the state so that I can display the data stored within different div elements. Here is my initial state: cons ...

Animating elements on a webpage can be achieved by using both

Is there a way to create an animation that moves objects based on button clicks? For example, when the "Monday" button is pressed, the object with the correct color will move down. If any other button like "Tuesday" is clicked, the previous object will mov ...

Guide for accessing and interpreting a random folder arrangement using JavaScript located alongside index.html

I am currently developing a testing reporting tool that organizes images into folders, resulting in a structure similar to this: root/ /counter/ img1.png img2.png /alarm/ img3.png The names of the folders like counter and alarm are not f ...

Tips for ensuring an element stays anchored at the bottom even when the keyboard is displayed

I recently encountered a situation on one of my pages where an element positioned at the bottom using absolute positioning was causing issues when the keyboard was opened, as it would move to the middle of the page unexpectedly. While this may seem like a ...