通过WebSockets发送位置更新的正确方法是什么?

时间:2014-03-10 20:22:05

标签: javascript node.js networking websocket socket.io

我需要在运行node.js的游戏世界中广播位置更新。我目前的想法是使用BinaryJS。不过,我不确定使用它的正确方法是什么。我想到了3个选项:

我目前在做什么,使用socket.io:我以编程方式存储在给定时间内发生的位置更新缓冲区,然后一次性发送:

setTimeout(function(){
    //called a fixed amount of times per second (40)
    //this variable will hold the accumulated position changes on the last 25ms
    //var accumulated_position_changes = [id0,x0,y0,z0, id1,x1,y1,z1...];
    client.send(accumulated_position_changes);
},25);

但是如果binary.js自己进行分块(是吗?),那么我是否应该在每次发生位置时不加选择地发送位置变化?

MyClass.prototype.set_position = function(x,y,z){
    // this is called thousands times a second
    this.x = x, this.y = y, this.z = z;
    client.send([this.id, x, y, z]);
};

或者我应该以某种方式创建一个派生node.js流的对象并使用它?也许用stream.write?或者其他方式?处理这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

在我的用例中,Binary.JS似乎每次写入管道时都会写一个数据包。

为什么不将位置更改写入缓冲区,然后使用Underscore.js'限制。您可以调用update()或其他任何内容,它会一次性写入整个缓冲区。您可以根据需要随时调用该函数,但请使用受限制的版本,以便它实际上最多只能运行50ms左右。

对于Web应用程序来说,这种延迟非常快。确保您正在考虑客户可以接收的速率并确认该信息。老实说,在成功发送和确认数据之前,我不会更新客户端。否则,某些人的更新率会过高。

相关问题