Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to send position updates via WebSockets?

I need to broadcast position updates in a game-world running with node.js. My current idea is to use BinaryJS. I'm not sure what is the correct way to use it, though. I have thought in 3 options:

How I'm doing currently, using socket.io: I programmatically store a buffer of position-updates that happened in a given amount of time and then send it all at once:

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

But if binary.js does the chunking by itself (does it?), then should I just indiscriminately send position changes every time they happen?

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

Or should I somehow create an object deriving node.js's stream and use it? Maybe with stream.write? Or some way else? What is the right way to deal with this problem?

like image 244
MaiaVictor Avatar asked Feb 04 '26 03:02

MaiaVictor


1 Answers

Binary.JS seems to write a packet every time you write to the pipe, in my use cases.

Why not write the position changes to a buffer, and then use Underscore.js' throttling. You could call update() or whatever, which writes the whole buffer of changes all at once. You can call that function as often as you want, but use the throttled version so that it only actually runs at a maximum of every 50ms or so.

That delay is incredibly fast for web applications. Be sure you are considering the rate at which your clients can receive and ACK that info. Honestly, I wouldn't update the clients until the data has successfully been sent and ACKed. Otherwise, you will have way too high of an update rate for some.

like image 138
Brad Avatar answered Feb 05 '26 19:02

Brad