-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
67 lines (53 loc) · 993 Bytes
/
main.go
File metadata and controls
67 lines (53 loc) · 993 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"encoding/json"
"funWithRealtime/hub"
"log"
"math/rand"
"net/http"
"time"
)
func main() {
h := hub.New()
go h.Run()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
hub.Serve(h, w, r)
})
qu := make(chan int, 100)
go func() {
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
for range ticker.C {
qu <- rand.Intn(9) + 1
}
}()
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
sum := 0
count := 0
draining := true
for draining {
select {
case v := <-qu:
sum += v
count++
default:
draining = false
}
}
if count == 0 {
continue
}
avg := float64(sum) / float64(count)
msg, _ := json.Marshal(map[string]any{
"avg": avg,
})
h.Broadcast <- msg
log.Println("Sent avg:", avg)
}
}()
log.Println("Server started at :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}