-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.go
86 lines (73 loc) · 1.95 KB
/
websocket.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
package stomp
import (
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"nhooyr.io/websocket"
)
type wssBroker struct {
httpServer *http.Server
}
// startWebsocketBroker is starts the STOMP broker on Websocket server
func startWebsocketBroker(opts *BrokerOpts) (*wssBroker, error) {
wss := &wssBroker{}
broker := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
wgSessions := &sync.WaitGroup{}
for {
c, err := websocket.Accept(w, r,
&websocket.AcceptOptions{
Subprotocols: []string{"v12.stomp"},
})
if err != nil {
log.Println(err)
break
}
conn := websocket.NetConn(context.Background(), c, websocket.MessageText)
wgSessions.Add(1)
go NewSession(conn, opts.LoginFunc, wgSessions, opts.HeartbeatSendIntervalMsec,
opts.HeartbeatReceiveIntervalMsec).Start()
}
wgSessions.Wait()
})
wss.httpServer = &http.Server{
Addr: opts.Host + ":" + opts.Port,
Handler: broker,
}
// Handle sigterm and await termChan signal
termChan := make(chan os.Signal, 2)
signal.Notify(termChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
<-termChan // Blocks here until interrupted
wss.Shutdown()
}()
return wss, nil
}
// ListenAndServe accepts the websocket client connections and servers the STOMP requests
func (wss *wssBroker) ListenAndServe() {
if err := wss.httpServer.ListenAndServe(); err != nil {
log.Println(err)
return
}
}
// Shutdown brings down the websocket server gracefully
func (wss *wssBroker) Shutdown() {
log.Println("Shutdown initiated ...")
if err := wss.httpServer.Shutdown(context.Background()); err != nil {
log.Println(err)
}
}
func startWebsocketClient(host, port string) (net.Conn, error) {
c, _, err := websocket.Dial(context.Background(), "ws://"+host+":"+port,
&websocket.DialOptions{
Subprotocols: []string{"v12.stomp"},
})
if err != nil {
return nil, err
}
return websocket.NetConn(context.Background(), c, websocket.MessageText), nil
}