Hello.
So I’ve got basic networking in my game working… (connecting, sending sending data …). Now it’s come time to synchronize client and server and first thing I need is determine ping between them. For simplicity, I assumed latency spike won’t occur and go ahead using TCP, not to mess with UDP and routers.
This is how I did it (obviusly I’m not satisfied):
When server authenticates the client (password if any is ok) then client starts a new thread that puts current time in a message and sends it (9 bytes, 1 byte ping_request header and 8 bytes long for nanoTime() ). Server upon receiving sends them back right away with ping_response header. Client reads value from message and substracts from nanoTime() so it gets ping time. I do that 5 times in 100ms interval.
Problems with this are that some messages get lost on the way to server, but this isn’t really so strange as I don’t deal with merged packets (yet) and I just use channel.write() without registring write on selector (again, yet).
Most of the times ping is correct on LAN, like 3 ms, but first time it’s ~30ms and sometimes when doing more pinging (like 20 times) I can get 150 or something like that. I’m interested is this sufficiant? Is new thread approach a way to go? Do I need stop all other net in/out and how often and how many times I need to do pinging to keep computers synchronized?
Here’s the thread code:
public void run() {
System.out.println("HP: Starting ping procedure.");
// Kova: sends 9 byte ping packet TIMES_TO_PING times in PING_INTERVAL ms interval
for(int i=0; i<TIMES_TO_PING; i++) {
System.out.println("HP: pinging for " + i + " time.");
write_buffer.clear();
write_buffer.put(PING_REQUEST);
write_buffer.putLong(System.nanoTime());
write_buffer.flip();
sendInstantMessage(write_buffer, sc); // does channel.write()
try {
Thread.sleep(PING_INTERVAL);
} catch (InterruptedException e) {
System.out.println("HP: Error sleeping, thread interrupted.");
e.printStackTrace();
}
}
System.out.println("HP: Ping procedure finished.");
} // end: thread, run()