-
Notifications
You must be signed in to change notification settings - Fork 17
/
broadcast.go
106 lines (94 loc) · 1.93 KB
/
broadcast.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//go:build ignore
// +build ignore
package main
import (
"fmt"
"os"
"os/signal"
"sync"
"time"
"github.com/buaazp/fasthttprouter"
"github.com/dgrr/fastws"
"github.com/valyala/fasthttp"
)
type Broadcaster struct {
lck sync.Mutex
cs []*fastws.Conn
}
func (b *Broadcaster) Add(c *fastws.Conn) {
b.lck.Lock()
b.cs = append(b.cs, c)
b.lck.Unlock()
}
func (b *Broadcaster) Start() {
for {
b.lck.Lock()
for i := 0; i < len(b.cs); i++ {
c := b.cs[i]
_, err := c.WriteString("Message")
if err != nil {
b.cs = append(b.cs[:i], b.cs[i+1:]...)
fmt.Println(len(b.cs))
continue
}
}
b.lck.Unlock()
time.Sleep(time.Second)
}
}
func main() {
b := &Broadcaster{}
router := fasthttprouter.New()
router.GET("/", rootHandler)
router.GET("/ws", fastws.Upgrade(func(c *fastws.Conn) {
b.Add(c)
for {
_, _, err := c.ReadMessage(nil)
if err != nil {
if err == fastws.EOF {
break
}
panic(err)
}
}
}))
go b.Start()
server := fasthttp.Server{
Handler: router.Handler,
}
go server.ListenAndServe(":8080")
fmt.Println("Visit http://localhost:8080")
sigCh := make(chan os.Signal)
signal.Notify(sigCh, os.Interrupt)
<-sigCh
signal.Stop(sigCh)
signal.Reset(os.Interrupt)
server.Shutdown()
}
func rootHandler(ctx *fasthttp.RequestCtx) {
ctx.SetContentType("text/html")
fmt.Fprintln(ctx, `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Sample of websocket with Golang</title>
</head>
<body>
<div id="text"></div>
<script>
var ws = new WebSocket("ws://localhost:8080/ws");
ws.onmessage = function(e) {
var d = document.createElement("div");
d.innerHTML = e.data;
ws.send(e.data);
document.getElementById("text").appendChild(d);
}
ws.onclose = function(e){
var d = document.createElement("div");
d.innerHTML = "CLOSED";
document.getElementById("text").appendChild(d);
}
</script>
</body>
</html>`)
}