How do I obtain the latency between server and client in C#?

Sorry that this isn’t directly answering your question, but generally speaking you shouldn’t rely too heavily on measuring latency because it can be quite variable. Not only that, you don’t know if the ping time you measure is even symmetrical, which is important. There’s no point applying 10ms of latency correction if it turns out that the ping time of 20ms is actually 19ms from server to client and 1ms from client to server. And latency in application terms is not the same as in networking terms – you may be able to ping a certain machine and get a response in 20ms but if you’re contacting a server on that machine that only processes network input 50 times a second then your responses will be delayed by an extra 0 to 20ms, and this will vary rather unpredictably.

That’s not to say latency measurement it doesn’t have a place in smoothing predictions out, but it’s not going to solve your problem, just clean it up a bit.

On the face of it, the problem here seems to be that that you’re sent information in the first message which you use to extrapolate data from until the last message is received. If all else stays constant then the movement vector given in the first message multiplied by the time between the messages will give the server the correct end position that the client was in at roughly now-(latency/2). But if the latency changes at all, the time between the messages will grow or shrink. The client may know he’s moved 10 units, but the server simulated him moving 9 or 11 units before being told to snap him back to 10 units.

The general solution to this is to not assume that latency will stay constant but to send periodic position updates, which allow the server to verify and correct the client’s position. With just 2 messages as you have now, all the error is found and corrected after the 2nd message. With more messages, the error is spread over many more sample points allowing for smoother and less visible correction.

It can never be perfect though: all it takes is a lag spike in the last millisecond of movement and the server’s representation will overshoot. You can’t get around that if you’re predicting future movement based on past events, as there’s no real alternative to choosing either correct-but-late or incorrect-but-timely since information takes time to travel. (Blame Einstein.)

Leave a Comment