-
Notifications
You must be signed in to change notification settings - Fork 0
/
transmitter.go
74 lines (67 loc) · 1.36 KB
/
transmitter.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
package main
import (
"github.com/gorilla/websocket"
"log"
"sync"
"time"
)
type transmitClient struct {
conn *websocket.Conn
nextChunk []byte
mutex sync.Mutex
ready chan struct{}
alive bool
shuttingDown bool
}
func newTransmitClient(conn *websocket.Conn) *transmitClient {
t := new(transmitClient)
t.conn = conn
t.ready = make(chan struct{}, 1)
return t
}
func (t *transmitClient) start() {
go func() {
if _, _, err := t.conn.NextReader(); err != nil {
t.alive = false
}
}()
go func() {
t.alive = true
for true {
<-t.ready
if !t.alive {
break
}
t.mutex.Lock()
c := append([]byte{}, t.nextChunk...)
t.mutex.Unlock()
if err := t.conn.WriteMessage(websocket.BinaryMessage, c); err != nil {
t.alive = false
}
}
log.Println("Closing websocket connection.")
if err := t.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseAbnormalClosure, "")); err == nil {
time.Sleep(5 * time.Second)
}
_ = t.conn.Close()
}()
}
func (t *transmitClient) close() {
if t.alive {
t.alive = false
t.signal()
}
}
func (t *transmitClient) signal() {
select {
case t.ready <- struct{}{}:
default:
log.Println("Dropping chunk due to slow client.")
}
}
func (t *transmitClient) send(chunk []byte) {
t.mutex.Lock()
t.nextChunk = chunk
t.mutex.Unlock()
t.signal()
}