// ****** Client time to server ****** // func sendOffsetToServer(serverTime time.Time) { // Calculate offset offset := myTime.Sub(serverTime) m := message.NewClockOffset(offset) log.Println("[Client] Client has offset of", offset) sendXmlToServer(m) }
// ****** Server time ****** // func sendTimeRequest(period time.Duration) { c := time.Tick(period) mutex := sync.Mutex{} for _ = range c { mutex.Lock() areWeGettingClocks = true time.AfterFunc(period/2, func() { // Stop getting clocks after n time and send updates log.Println("[Server] Stop recieving time") // Sanity check, if no one is here return if len(connections) == 0 { return } areWeGettingClocks = false var sumOfClocks int64 var computedCloks int64 for _, c := range userClocks { // FIXME // Calculate average // TODO Probably should check for overflow log.Println("[Server] user clocks", userClocks) log.Println("[Server] ", c) if c.Timestamp == nil { continue } sumOfClocks += c.Timestamp.Unix() computedCloks++ } if computedCloks == 0 { return } average := sumOfClocks / computedCloks log.Println("[Server] Clock average", average) // Create new time object and send to users // "0" since we don't have nanoseconds averageTime := time.Unix(average, 0) // Then send that average to all users that need to adjust their clocks // Now send it to all users for i, u := range userClocks { // This gives me an offset. // FIXME if u.Timestamp == nil { continue } adjustment := averageTime.Sub(*u.Timestamp) m := message.NewClockOffset(adjustment) log.Println("[Server] Adjustment for user", i, adjustment) log.Println("[Server] Becasue user has", *u.Timestamp) mm, _ := xml.Marshal(m) // Get user reference usr, ok := connections[u.User.String()] if !ok { log.Println("[Server] error sending message to user with address", userClocks[i].User.String()) } sendMessageToUser(usr, mm) } // Finally, clear slice userClocks = userClocks[:0] }) // For server time is always time.Now, since he // doesn't adjust his clock m := message.NewClockSyncPetition(time.Now()) mm, _ := xml.Marshal(m) log.Println("[Server] Sending time to user", m) for _, u := range connections { sendMessageToUser(u, mm) } mutex.Unlock() } }