As th ball has a fixed equation describing its motion, you should be able to sync without worrying too much about time. Anyway, thats an extra complication for now

To sync a clock, you basically decide which client is going to run the 'master clock' This 'resets' the clock by storing the current time. Thenthe game time is 'currentTimeInMillis - startTime'.
The other client must ask for a time update, sending a request number with the message, and recording when it sent the message '
msgTime' and what number it used.
The master clock respons immediately to the message with the current game time (currentTime - startTime).
The other client receives this, and matches it to the stored sent request (using the request number I mentioned earlier), also noting the time it received the message '
recvTime'. Note all client times can be done with the currentTimeMillis as we are going to be taking differences.
The approximate 'game time' for this client is then:
approxGameTime = receivedGameTime + ((recvTime - msgTime)>>1);
This is adding on half the round trip time (RTT).
However, that is not the end of it. You have to account for variations in the transmission.
To do this:
For the first timer message received just set gameClock and store RTT as 'bestRTT'
For each subsequent clock update:
1 2 3 4 5 6 7 8 9 10 11 12
| RTT = recvTime - msgTime; if( RTT < bestRTT ) { gameTime = (approxGameTime + gameTime)>>1; bestRTT = RTT; } else if( RTT < bestRTT + (bestRTT>>2) ) { gameTime = (3*gameTime + approxGameTime)>>2; } clockOffset = gameTime - System.currentTimeMillis(); |
then the client has an offset he can use to get the game time:
1 2 3 4
| long GetGameTime() { return (clockoffset - System.currentTimeMillis()); } |
This is a simple way of getting an OK shared clock.
To do it properly, you should measure the standard deviation of the RTTs, and use a weighted average based on this (instead of the 25% of best RTT I use above). This will give a better update behaviour over a noisy network than the scheme here, but this should work ok for a local area network or a good internet connection.
Apologies in advance for typos, syntax errors, & getting my +/- signs the wrong way around

Hope this helps,
- Dom