Socket.io和Node / Express - 超出最大调用堆栈大小

[英]Socket.io 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!

PS:这是我第一次导入代码,它不会让我缩进它!

Server Side code:

服务器端代码:

var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(8000);
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!');
        console.dir(event.target);
        socket.emit('myClick', {id: event.target});
    });
    socket.on('myClick', function (data) {
        console.log('event hit other client');
        $(data.id).trigger('click');
    });
});

1 个解决方案

#1


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:

更具体的东西,比如必须触发事件的元素的id或类:

$("#elementId").on('click', function(event){
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/07/27/7202f05c4efe091a42a78412af648ed4.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告