-
Notifications
You must be signed in to change notification settings - Fork 13
/
socket.go
103 lines (81 loc) · 1.94 KB
/
socket.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
package socket
import (
"context"
"encoding/json"
"time"
"github.com/gorilla/websocket"
errorlogger "github.com/coretrix/hitrix/service/component/error_logger"
)
type Connection struct {
Ws *websocket.Conn
Send chan []byte
}
type Socket struct {
Ctx context.Context
ErrorLogger errorlogger.ErrorLogger
Connection *Connection
ID string
Namespace string
}
func (c *Connection) write(mt int, payload []byte) error {
_ = c.Ws.SetWriteDeadline(time.Now().Add(writeWait))
return c.Ws.WriteMessage(mt, payload)
}
func (s *Socket) ReadPump(registry *Registry, readMessageHandler func(rawData []byte)) {
defer func() {
registry.Unregister <- s
s.Connection.Ws.Close()
}()
s.Connection.Ws.SetReadLimit(maxMessageSize)
_ = s.Connection.Ws.SetReadDeadline(time.Now().Add(pongWait))
s.Connection.Ws.SetPongHandler(func(string) error {
_ = s.Connection.Ws.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
_, rawData, err := s.Connection.Ws.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
s.ErrorLogger.LogError(err)
}
break
}
readMessageHandler(rawData)
}
}
func (s *Socket) WritePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
s.Connection.Ws.Close()
}()
for {
select {
case message, ok := <-s.Connection.Send:
if !ok {
err := s.Connection.write(websocket.CloseMessage, []byte{})
if err != nil {
s.ErrorLogger.LogError(err)
}
return
}
if err := s.Connection.write(websocket.TextMessage, message); err != nil {
s.ErrorLogger.LogError(err)
return
}
case <-ticker.C:
if err := s.Connection.write(websocket.PingMessage, []byte{}); err != nil {
s.ErrorLogger.LogError(err)
return
}
}
}
}
func (s *Socket) Emit(dto interface{}) {
data, err := json.Marshal(dto)
if err != nil {
s.ErrorLogger.LogError(err)
return
}
s.Connection.Send <- data
}