如何保持套接字在setInterval中发送数据

时间:2015-01-09 16:29:50

标签: javascript node.js sockets

我正在尝试使用socket.io将数据发送到节点服务器。我有完美的连接,但数据并没有像我想的那样过来。目前在我的网页中我有一个使用webGl设置的画布,在这个webGl中我使用setInterval方法在画布上生成球。我有一个数组,其中包含这个球列表,我希望能够跟踪每个球的位置,直到它们离开屏幕。目前,我所得到的只是每个球被发送到服务器的第一个位置,但我认为这是由于我放置了套接字。但是当我移动套接字代码时,我松开了对球位置的引用。

我设置了这样的计时器和变量:

var ballArray =[];
var i = 0;
//The timer for creating the balls at a set interval
var timer = setInterval(function() { addBall() }, 600);

因此将tiumer设置为600毫秒并调用addBall()函数。

    //Checks to make sure there is a set amount of balls and does not grow too large
    function addBall()
        {
            if(i <= 10)
            {
                createBall();
                scene.add(ballArray[i]);
                i++;
                console.log(i);
            }
            else
            {
                console.log("Finished");
                clearInterval(timer);
            }
        }

如果屏幕上有超过11个球,则tiomer将停止,否则它会在createBall()函数中生成一个新球:

function createBall()
        {
            //create the ball object with physics
            ball = new Physijs.SphereMesh(
            new THREE.SphereGeometry(Math.random() * (4 - 1) + 1,16,16),
            Physijs.createMaterial(new THREE.MeshLambertMaterial(
            {
                color: 0xff0000,
                reflectivity: 0.8
            }),0.4,0.6),1 );
            //Positioning data
            var r = 
            {
                x: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12,
                y: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12,
                z: Math.random() * (Math.PI - Math.PI / 12) + Math.PI / 12
            };

            //Setting the pos of the ball
            ball.rotation.set(r.x, r.y, r.z);
            ball.position.y = 40;
            ball.castShadow = true;
            ball.receiveShadow = true;
            ballArray[i] = ball;
            //sending the data of the ball to the sever
            socket.emit('Ball',  { name : "ballArray"+i, X : ballArray[i].position.x, Y : ballArray[i].position.y, Z : ballArray[i].position.z});
        }

然后设置球的所有条件,球将产生,然后我设置我的套接字发送信息。 我想因为我在设定的时间间隔内调用它,套接字发送一次,然后再次发送下一个球而不是为所有球不断发送数据。我知道我可以使用阵列来获得一定数量的球,但我希望能够及时取出球数限制。 有没有办法解决这个问题,还是我必须重新编写这部分代码以更好地实现我想要做的事情? 任何guidancxe将不胜感激!

1 个答案:

答案 0 :(得分:0)

您希望在更新功能中定期传输数据,而不是在createBall功能中传输数据。因此,在每个帧调用的更新函数中,您将遍历数组,并且每个现有的球都会传输数据。

最好将所有球分组到一个包中,而不是每个框架,但我想这些与性能有关的事情你可能还不会担心。