Socket IO: Error - The call stack has exceeded the maximum size limit

Whenever a client connects to my node.js server, it crashes with a 'RangeError: Maximum call stack size exceeded' error. I suspect there's a recursive problem somewhere in my code that I can't seem to find.

This is the code on my server:

require('monitor').start();
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

var allClients = [];

io.on('connection', function(socket){
  console.log('user joined: ' + socket.request.connection.remoteAddress + ':' + socket.request.connection.remotePort);
  socket.address = socket.request.connection.remoteAddress;
  socket.port = socket.request.connection.remotePort;
  socket.name = '';
  socket.xPos = 0;
  socket.yPos = 0;

  // Send current client list to new connection
  socket.emit('client list', allClients);

  // Broadcast 'new user' event to existing clients only
  var i = 0;
  for(i=0;i<allClients.length;i++){
    allClients[i].emit('new user', socket.address + '_' + socket.port);
  }

  // Add new socket to the client array after sending it to other users
  allClients.push(socket);

  socket.on('chat message', function(msg){
    io.emit('chat message', socket.address + ':' + socket.port + ": " + socket.name + ' says: ' + msg);
    console.log(socket.address + ":" + socket.port + ": " + socket.name + ' says: ' + msg);
  });

    socket.on('set_name', function(msg){
    socket.name = msg;
    console.log(socket.address + ":" + socket.port + ' set name to: ' + msg);
  });

  socket.on('xPosUpdate', function(msg){
    console.log(socket.address + ":" + socket.port + ' set xPos to: ' + msg);
  });

  socket.on('yPosUpdate', function(msg){
    console.log(socket.address + ":" + socket.port + ' set yPos to: ' + msg);
  });

  socket.on('disconnect', function() {
    io.emit('user disconnect', socket.address + '_' + socket.port);
    io.emit('chat message', socket.address + ':' + socket.port + ": " + socket.name + ' disconnected.');
      console.log('Got disconnect!');
    socket = null;
      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

And here's how I'm handling the socket on the client side:

var users = [];
$('#chatInput').submit(function(){
  socket.emit('chat message', $('#m').val());
  $('#m').val('');
  return false;
});
$('#nameInput').submit(function(){
  socket.emit('set_name', $('#n').val());
  $('#n').val('');
  return false;
});
socket.on('client list', function(msg){
  $('#messages').append($('<li>').text('Processing client list...'));
    var i = 0;
  for(i=0;i<msg.length;i++){
    $('#messages').append($('<li>').text('Client ' + i + ': ' + msg[i].address + ':' + msg[i].port + ', Name: ' + msg[i].name));
  }
});
socket.on('chat message', function(msg){
  $('#messages').append($('<li>').text(msg));
});
socket.on('user disconnect', function(msg){
  users[msg].unset();
});
socket.on('new user', function(msg){
  users[msg] = [];
  users[msg].xPos = 0;
  users[msg].yPos = 0;
  $('#messages').append($('<li>').text(msg));
});

Answer №1

Appreciate the replies.

After some trial and error, I discovered that the overflow issue was being triggered by the extensive amount of data I was trying to send in the following server line:

socket.emit('client list', allClients);

Each time a new user connects, I am adding the complete connection object to the "allClients" array. The size of data within a connection object is too large for socket.emit, resulting in the RangeError.

To prevent this "stack overflow", I need to streamline the client list data sent to each new client...

Answer №2

Instead of running a loop, you can achieve the same result with this code snippet:

socket.broadcast.emit('new user', socket.address + '_' + socket.port);

You can then eliminate the following lines:

socket = null;
var i = allClients.indexOf(socket);
allClients.splice(i, 1);

However, I'm not entirely certain if that is the issue at hand. I suspect it may be related to socket.name = msg;. It might be best to remove this line.

Answer №3

// Let's only send the 'new user' event to clients that were previously connected, excluding the new client.
  var counter = 0;
  for(counter=0;counter<allClients.length;counter++){
    allClients[counter].emit('new user', socket.address + '_' + socket.port);
  }

I find the code snippet above to be somewhat questionable. Have you verified the value of allClients.length? Also, it seems redundant to initialize the variable i twice in this situation.

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

`Switching between two buttons: A guide`

Here is the codepin: https://jsfiddle.net/magicschoolbusdropout/dwbmo3aj/18/ I currently have a functionality in my code that allows me to toggle between two buttons. When I click on one button, content opens and then closes when clicked again. The same b ...

Are these two glob patterns distinct from each other in any way?

images/**/*.{png,svg} images/**/*.+(png|svg) After running tests on both expressions, it appears that they generally yield identical outcomes. However, it is crucial to confirm that they are indeed equivalent. ...

Information displays instantly in the initial milliseconds

When developing dynamic web pages with Nuxt, I encountered an issue in the pages directory where a file named _url.vue is located. The contents of this file are as follows: <template lang="pug"> div component( v-for= ...

The image fails to display correctly

As I work on creating a basic webpage in HTML and JavaScript, my goal is to validate certain parameters (such as width, height) of an image that users upload via a form. In JavaScript, I extract the file from the form and attempt to display it as an image ...

Obtaining images from the backend within a component's TypeScript file in a MEAN stack application is a

In my component.ts file, I am looking to retrieve images from the backend/images folder as Image objects. The paths of these images are stored in the database. this.productsService.getProduct(this.editId).subscribe(productData => { this.name = prod ...

IMAP feature being phased out by Gmail?

Recently, I came across an interesting article stating that IMAP will be disabled by September 2024. Google plans to implement OAuth for enhanced security and protection for third-party apps. So, the question is, once IMAP is disabled, will developers or c ...

Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in: <form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1"> <div id="main_body" class="full-width"> <label>User ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

Extract distinct values along with their respective counts from an array containing objects

Upon receiving a JSON request containing an array of objects with two properties, the task at hand is to extract the unique values along with their respective quantities. The following JSON data is being sent through Postman: [ {"name": "First value" ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

When attempting to load a JSON file, a Node.js loader error is triggered stating "Error: Cannot find module 'example.json'" while running transpiled code through Babel

When it comes to importing or requiring JSON (.json) files in TypeScript code, there have been multiple questions addressing similar issues. However, my query specifically pertains to requiring a JSON file within an ES6 module that is transpiled to the cur ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Searching in the Kendo Dropdown List using text and value

$(document).ready(function() { $("#selection").kendoDropDownList({ filter: "startswith", dataTextField: "SelectionName", dataValueField: "SelectionID", dataSour ...

Is there a way to run JavaScript using Selenium and extract information at the same time?

Greetings and thank you for taking the time to read this. I am currently working on a parser that scans hundreds of websites to check if they have a specific module or plugin installed. The main challenge I am facing is determining whether a website utili ...

Has xlink:href become outdated for svg <image> elements?

In the realm of SVG attributes, it is noted by MDN xlink:href that href should be used over xlink:href. Interestingly, on the svg example page, last revised on July 6, 2017, the attribute utilized in the given example is xlink:href. The question arises: ...

Is there a way to conceal JavaScript code?

I am trying to keep my AJAX code hidden from users who view the source of my PHP page. How can I achieve this? Below is the AJAX code that I currently have: <script type="text/javascript"> function Ajax(){ var xmlHttp; try{ xmlHttp=n ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

Expand the grid with extra rows once it has been generated, especially when dealing with a large volume of database records, utilizing JQGrid or JSGrid

Having a large dataset (json) that takes too long to display in the grid for users, I'm looking for a solution. My idea is to initially run a filtered query (e.g. records from the current year) to quickly build the grid. Once the grid is presented to ...