-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
115 lines (95 loc) · 2.29 KB
/
controller.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
109
110
111
112
113
114
115
package socketconsumer
import (
"bytes"
"log"
"time"
"github.com/gorilla/websocket"
)
type ConsumerController struct {
cons *ConsumerInterface
hub *Hub
conn *websocket.Conn
sendChan chan []byte
}
func NewConsumerController(hub *Hub, conn *websocket.Conn, cons *ConsumerInterface) *ConsumerController {
return &ConsumerController{
cons: cons,
hub: hub,
conn: conn,
sendChan: make(chan []byte),
}
}
// open opens the consumer
func (cc *ConsumerController) open() {
cc.hub.RegisterConsumer(cc)
(*cc.cons).Accept()
}
// close closes the consumer
func (cc *ConsumerController) close() {
(*cc.cons).Disconnect()
cc.hub.UnregisterConsumer(cc)
cc.conn.Close()
close(cc.sendChan)
}
// Get id
func (cc *ConsumerController) getId() string {
return (*cc.cons).GetId()
}
// Send message
func (cc *ConsumerController) send(message *Message) {
cc.sendChan <- message.ToJson()
}
// read message from websocket
func (cc *ConsumerController) WebsocketReceive() {
defer cc.close()
cc.conn.SetReadDeadline(time.Now().Add(pongWait))
cc.conn.SetPongHandler(func(string) error { cc.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := cc.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
(*cc.cons).Receive(NewMessageFromJson(message))
}
}
// Write message to websoket
func (cc *ConsumerController) WebsocketSend() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
cc.conn.Close()
}()
for {
select {
case message, ok := <-cc.sendChan:
if !ok {
cc.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := cc.conn.NextWriter(websocket.TextMessage)
if err != nil {
log.Println(err)
return
}
w.Write(message)
// Add queued chat messages to the current websocket message.
n := len(cc.sendChan)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-cc.sendChan)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
if err := cc.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
log.Println(err)
return
}
}
}
}