Refactor the poll offer to use a ticker

Simplify the code to use a ticker. Using a pattern to allow a first run
of the loop before hitting the ticker:
https://github.com/golang/go/issues/17601#issuecomment-311955879
This commit is contained in:
meskio 2021-07-21 12:01:07 +02:00
parent b4e964c682
commit 099f4127ea
No known key found for this signature in database
GPG key ID: 52B8F5AC97A2DA86

View file

@ -123,19 +123,12 @@ func (s *SignalingServer) Post(path string, payload io.Reader) ([]byte, error) {
func (s *SignalingServer) pollOffer(sid string) *webrtc.SessionDescription { func (s *SignalingServer) pollOffer(sid string) *webrtc.SessionDescription {
brokerPath := s.url.ResolveReference(&url.URL{Path: "proxy"}) brokerPath := s.url.ResolveReference(&url.URL{Path: "proxy"})
timeOfNextPoll := time.Now()
for {
// Sleep until we're scheduled to poll again.
now := time.Now()
time.Sleep(timeOfNextPoll.Sub(now))
// Compute the next time to poll -- if it's in the past, that
// means that the POST took longer than pollInterval, so we're
// allowed to do another one immediately.
timeOfNextPoll = timeOfNextPoll.Add(pollInterval)
if timeOfNextPoll.Before(now) {
timeOfNextPoll = now
}
ticker := time.NewTicker(pollInterval)
defer ticker.Stop()
// Run the loop once before hitting the ticker
for ; true; <-ticker.C {
numClients := int((tokens.count() / 8) * 8) // Round down to 8 numClients := int((tokens.count() / 8) * 8) // Round down to 8
body, err := messages.EncodePollRequest(sid, "standalone", currentNATType, numClients) body, err := messages.EncodePollRequest(sid, "standalone", currentNATType, numClients)
if err != nil { if err != nil {
@ -163,6 +156,7 @@ func (s *SignalingServer) pollOffer(sid string) *webrtc.SessionDescription {
} }
} }
return nil
} }
func (s *SignalingServer) sendAnswer(sid string, pc *webrtc.PeerConnection) error { func (s *SignalingServer) sendAnswer(sid string, pc *webrtc.PeerConnection) error {