简体   繁体   English

socket.io在for循环中使用socket.on执行函数

[英]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 handupCards是客户端使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM