带socket.io的循环在开头终止

时间:2012-12-08 11:31:23

标签: javascript node.js loops socket.io

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

问题是,当代码到达 AddTile emit函数时,它会在那里停止并且没有任何反应。服务器没有收到请求,循环终止。

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

 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);
        }
      //

    });
  });

1 个答案:

答案 0 :(得分:2)

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