【问题标题】:Loop with socket.io terminates at the beginning带有 socket.io 的循环在开头终止
【发布时间】:2012-12-08 11:31:23
【问题描述】:

我正在构建此功能以将小图块图像上传到服务器。 客户端构建 tileBuffer,然后调用 fireTiles 函数。 这里我想基于tileBuffer.length构建一个循环。服务器将处理控制。因此,我发出 StartAddTiles 并立即使用 AnotherTile 事件从服务器回调。调试器显示我已被服务器调用,我看到代码进入 socket.on('AnotherTile'... 语句。

问题在于,当代码到达 AddTile 发射函数时,它会停在那里,什么也没有发生。服务器没有收到请求,循环在那里终止。

我的代码中的错误在哪里?

 function fireTiles (tileBuffer, mapSelected) {

        var tiles =   tileBuffer.length;
        var tBx = 0;

        try
        {
            var socket = io.connect('http://myweb:8080/');

            socket.emit('StartAddTiles', tiles, mapSelected);   
            socket.on('AnotherTile', function (tlN){
                if (tlN < tiles) {
                    var data = tileBuffer[tlN];  //uso tlN per far comandare il server
                    tBx++; // debug purpose
                    socket.emit('AddTile', mapSelected, data, tBx);
                } else {
                // something went wrong
                    alert('Error calculating tiles');
                    return;
                }
            });
        }
        catch(err)
        {
            document.getElementById('status').innerHTML = err.message;
        }


    } 

这里是服务器端:

io.sockets.on('connection', function(client) {
  console.log('Connecting....');
// controls are limited, this is just a beginning

  // Initiate loop
  client.on('StartAddTiles', function(tiles, mapSelected) {
    var mapId = mapSelected;
    mapLoading[mapId] = {  //Create a new Entry in The mapLoading Variable
    tilesToLoad : tiles,
    tilesLoaded : 0
    }
     console.log('Start loading '+mapLoading[mapId].tilesToLoad+' tiles.');
    // Ask for the first tile
    client.emit('AnotherTile', mapLoading[mapId].tilesLoaded);
      //

  });

  // client add new Tile/Tiles
  client.on('addTile', function(mapSelected, data, tBx) {
    var mapId = mapSelected;
    mapLoading[mapId].tilesLoaded = ++1;
    console.log('Adding tile '+mapLoading[mapId].tilesLoaded+' of '+mapLoading[mapId].tilesToLoad+' tBx '+tBx);

    // insert Tile
    db_manager.add_tiles(tileBuffer, function(result) {

        if (mapLoading[mapId].tilesLoaded == mapLoading[mapId].tilesToLoad) {  // full map loaded
        mapLoading[mapId] = "";  //reset the buffer
        client.emit('TilesOk', mapLoading[mapId].tilesLoaded);
        } else {
        console.log('requesting tile num: '+mapLoading[mapId].tilesLoaded);
        client.emit('AnotherTile', mapLoading[mapId].tilesLoaded);
        }
      //

    });
  });

【问题讨论】:

  • 你也可以显示服务器端代码吗?
  • 我觉得自己很蠢 ;-) 非常感谢
  • 不,你不应该这样。这种事情只是发生

标签: javascript node.js loops socket.io


【解决方案1】:

事件名称区分大小写,您应该在服务器端也使用AddTile 而不是addTile

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 1970-01-01
    • 2014-10-19
    • 2022-09-24
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    相关资源
    最近更新 更多