-
Notifications
You must be signed in to change notification settings - Fork 0
/
sock.go
69 lines (63 loc) · 1.45 KB
/
sock.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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"net"
)
var SockPort = flag.Int("sockport", 7897, "port used for streaming temperature temps")
func StartSockServer() chan HistorySample {
stream := make(chan HistorySample, 1)
ready := make(chan bool)
toSock := make(chan []byte, 1)
go dispatchStream(stream, ready, toSock)
go listenSock(ready, toSock)
return stream
}
func dispatchStream(
stream chan HistorySample, ready chan bool, toSock chan []byte) {
sockReady := false
for {
select {
case sample := <-stream:
if (!sockReady) {
continue
}
msg, err := json.Marshal(sample)
if err != nil {
log.Printf("warning: could not stream snapshot: %v", err)
continue
}
toSock <- msg
case sockReady = <-ready:
// all good
}
}
}
func listenSock(ready chan bool, toSock chan []byte) {
ss, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", *SockPort))
if err != nil {
log.Fatalf("error: could not listen on %d: %v", *SockPort, err)
}
for {
log.Printf("accepting new client on :%d", *SockPort)
sock, err := ss.Accept()
if err != nil {
log.Printf("warning: could not accept on socket: %v", err)
}
log.Printf("sending snapshots to client %v", sock.RemoteAddr())
ready <- true
for {
msg := <-toSock
_, err := sock.Write(msg)
if err != nil {
log.Printf("warning: failed to write to socket: %v", err)
break
}
_, err = sock.Write([]byte("\n\x00"))
}
ready <- false
sock.Close()
}
}