-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (88 loc) · 2.12 KB
/
main.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
107
108
package main
import (
"log"
"net"
"os"
"os/signal"
"time"
"github.com/gorilla/websocket"
)
const (
writeWait = 10 * time.Second
pongWait = 30 * time.Second
pingPeriod = (pongWait * 9) / 10
maxMessageSize = 512
)
func main() {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
url := os.Getenv("WSS_URL")
log.Printf("connecting to %s", url)
addr, err := net.ResolveUDPAddr("udp", "239.228.217.206:12345")
if err != nil {
log.Fatalf("udp error: %v", err)
return
}
udp, err := net.DialUDP("udp", nil, addr)
if err != nil {
log.Fatalf("udp error: %v", err)
return
}
defer udp.Close()
ws, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
log.Fatal(err)
return
}
defer ws.Close()
ticker := time.NewTicker(pingPeriod)
ws.SetReadLimit(maxMessageSize)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error {
ws.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Fatalf("read error: %v", err)
}
break
}
log.Printf("received message: %s", message)
_, err = udp.Write(message)
if err != nil {
log.Fatalf("udp write error: %v", err)
}
}
}()
for {
select {
case <-done:
return
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil {
log.Fatalf("write error: %v", err)
return
}
select {
case <-done:
}
return
case <-ticker.C:
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Fatalf("write error: %v", err)
return
}
}
}
}