Socket.io和Node / Express - 超出最大調用堆棧大小

[英] and Node/Express - Maximum call stack size exceeded

I'm using react on front end and node/express on backend. I am trying to integrate sockets to make any click event done on one client be emitted on all the other clients. (ex. if someone clicks 'play song' it will trigger a click event for all the other users to play the song).

我正在前端使用react和后端使用node / express。我正在嘗試集成套接字,以便在所有其他客戶端上發出在一個客戶端上完成的任何單擊事件。 (例如,如果有人點擊“播放歌曲”,它將觸發所有其他用戶播放歌曲的點擊事件)。

When I click on something, it doest reach the server's socket listener and displays Maximum call stack size exceeded in the browser's console.


PS: it's my first time importing code and it wont let me indent it!


Server Side code:


var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('')(server);
io.on('connection', function (socket) {
    console.log('socket connected!');
    socket.on('myClick', function (data) {
        console.log('event hit Server');
        socket.broadcast.emit('myClick', data);
    socket.on('disconnect', function () {
        io.emit('user disconnected');

Client Side Code:


$(document).ready(function () {
    var socket = io('http://localhost:8000');

    $(document).on('click', function(event){
        console.log('Something has been clicked!');
        socket.emit('myClick', {id:});
    socket.on('myClick', function (data) {
        console.log('event hit other client');

1 个解决方案



Your error is at the client side, you are causing an infinite loop of calls:


  1. When clicking on the DOM, your "click" function is fired.
  2. 單擊DOM時,會觸發“單擊”功能。

  3. That function emits the socket's "myClick" event, so the "myClick" function is fired.
  4. 該函數發出套接字的“myClick”事件,因此觸發了“myClick”函數。

  5. Inside this function you trigger a click event, and so, the previous function is fired again and you go back to step 1 infinitely.
  6. 在此函數內部,您會觸發單擊事件,因此,再次觸發上一個函數,然后無限地返回到步驟1。

Solution: replace the


$(document).on('click', function(event){

line with something more specific, like the id or the class of the element which has to fire the event:


$("#elementId").on('click', function(event){



粤ICP备14056181号  © 2014-2021