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
Your error is at the client side, you are causing an infinite loop of calls:
您的錯誤發生在客戶端,導致無限循環調用:
單擊DOM時,會觸發“單擊”功能。
該函數發出套接字的“myClick”事件,因此觸發了“myClick”函數。
在此函數內部,您會觸發單擊事件,因此,再次觸發上一個函數,然后無限地返回到步驟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){
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/07/27/7202f05c4efe091a42a78412af648ed4.html。