[英]socket.io Using socket.on inside a for loop to execute a function
I have some code for an online multiplayer game using socket.io
. 我有一些使用
socket.io
进行在线多人游戏的代码。 At one point, clients send data to the server, to receive and process this data I have a socket.on inside a for loop. 一方面,客户端将数据发送到服务器,以接收和处理此数据,我在for循环中有一个socket.。
Server: 服务器:
function callBack(hand, upCards) {
return function() {
io.to('game_room').emit('log', 'callback');
players[i].socket.off('swapdone', runSwap);
players[i].swapped = true;
io.to('game_room').emit('log', 'call doswap');
doSwap(i, hand, upCards);
};
};
for (i = 0; i < players.length; i++ ){
players[i].socket.on('swapdone', function(hand, upCards) {
return callBack(i, hand, upCards);
});
};
hand
and upCards
are arrays sent from the client using socket.emit
hand
和upCards
是客户端使用socket.emit
发送的数组
Initially my problem was due to not using a callback function to avoid the closure issue, however now I've added a separate callBack
function to fix this. 最初,我的问题是由于没有使用回调函数来避免关闭问题,但是现在我添加了一个单独的
callBack
函数来解决此问题。
The problem now is that when the client sends the 'swapdone'
signal, the code inside the callBack
function is not executed. 现在的问题是,当客户端发送
'swapdone'
信号时,不会执行callBack
函数中的代码。 I've tried moving functions around but I always get either the closure-callback problem, or the function doesn't execute. 我尝试过移动函数,但是总是遇到闭包回调问题,或者函数无法执行。
What am I missing? 我想念什么?
callBack
takes two parameters, you pass three arguments. callBack
有两个参数,您传递了三个参数。 i
should be the first parameter of the function. i
应该是函数的第一个参数。 Additionally you have to properly declare i
: 另外,您必须正确声明
i
:
for (let i = 0; i < players.length; i++ ){
Additionally the inner function in callBack
is useless, as it does nothing. 另外,
callBack
的内部函数是无用的,因为它什么也不做。 Just remove that. 删除它。
How I would do that: 我该怎么做:
function callBack(i) {
return function(hand, upCards) {
io.to('game_room').emit('log', 'callback');
players[i].socket.off('swapdone', runSwap);
players[i].swapped = true;
io.to('game_room').emit('log', 'call doswap');
doSwap(i, hand, upCards);
};
}
for (let i = 0; i < players.length; i++ ){
players[i].socket.on('swapdone', callBack(i));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.