forked from muka/peerjs-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.go
202 lines (171 loc) · 4.08 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package peer
import (
"encoding/json"
"fmt"
"strconv"
"sync"
"time"
"github.com/muka/peerjs-go/emitter"
"github.com/muka/peerjs-go/enums"
"github.com/muka/peerjs-go/models"
"github.com/gorilla/websocket"
"github.com/sirupsen/logrus"
)
// SocketEvent carries an event from the socket
type SocketEvent struct {
Type string
Message *models.Message
Error error
}
//NewSocket create a socket instance
func NewSocket(opts Options) *Socket {
s := &Socket{
Emitter: emitter.NewEmitter(),
log: createLogger("socket", opts.Debug),
}
s.opts = opts
s.disconnected = true
return s
}
//Socket abstract websocket exposing an event emitter like interface
type Socket struct {
emitter.Emitter
id string
opts Options
baseURL string
disconnected bool
conn *websocket.Conn
log *logrus.Entry
mutex sync.Mutex
wsPingTimer *time.Timer
}
func (s *Socket) buildBaseURL() string {
proto := "ws"
if s.opts.Secure {
proto = "wss"
}
port := strconv.Itoa(s.opts.Port)
path := s.opts.Path
if path == "/" {
path = ""
}
return fmt.Sprintf(
"%s://%s:%s%s/peerjs?key=%s",
proto,
s.opts.Host,
port,
path,
s.opts.Key,
)
}
func (s *Socket) scheduleHeartbeat() {
s.wsPingTimer = time.AfterFunc(time.Millisecond*time.Duration(s.opts.PingInterval), func() {
s.sendHeartbeat()
})
}
func (s *Socket) sendHeartbeat() {
if s.conn == nil {
s.log.Debug(`Cannot send heartbeat, because socket closed`)
return
}
msg := models.Message{
Type: enums.ServerMessageTypeHeartbeat,
}
res, err := json.Marshal(msg)
if err != nil {
s.log.Errorf("sendHeartbeat: Failed to serialize message: %s", err)
}
// s.log.Debug("Send heartbeat")
err = s.Send(res)
if err != nil {
s.log.Errorf("sendHeartbeat: Failed to send message: %s", err)
}
s.scheduleHeartbeat()
}
//Start initiate the connection
func (s *Socket) Start(id string, token string) error {
if !s.disconnected {
return nil
}
if s.baseURL == "" {
s.baseURL = s.buildBaseURL()
}
url := s.baseURL + fmt.Sprintf("&id=%s&token=%s", id, token)
s.log.Debugf("Connecting to %s", url)
c, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return err
}
s.conn = c
s.conn.SetCloseHandler(func(code int, text string) error {
// s.log.Debug("WS closed")
s.disconnected = true
s.conn = nil
return nil
})
// ws ping by sending heartbeat message
s.scheduleHeartbeat()
// collect messages
go func() {
for {
if s.conn == nil {
s.log.Debug("WS connection unset, closing read go routine")
return
}
msgType, raw, err := s.conn.ReadMessage()
s.log.Debugf("WS msg %v", msgType)
if err != nil {
// catch close error, avoid panic reading a closed conn
if _, ok := err.(*websocket.CloseError); ok {
s.log.Debugf("websocket closed: %s", err)
s.Emit(enums.SocketEventTypeDisconnected, SocketEvent{enums.SocketEventTypeDisconnected, nil, err})
return
}
s.log.Warnf("websocket read error: %s", err)
continue
}
s.log.Infof("websocket message: %s", raw)
if msgType == websocket.TextMessage {
msg := models.Message{}
err = json.Unmarshal(raw, &msg)
if err != nil {
s.log.Errorf("Failed to decode websocket message=%s %s", string(raw), err)
}
s.Emit(enums.SocketEventTypeMessage, SocketEvent{enums.SocketEventTypeMessage, &msg, err})
} else {
s.log.Warnf("Unmanaged websocket message type %d", msgType)
}
}
}()
return nil
}
//Close close the websocket connection
func (s *Socket) Close() error {
if s.disconnected {
return nil
}
err := s.conn.WriteMessage(
websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
)
if err != nil {
s.log.Debugf("Failed to send close message: %s", err)
}
err = s.conn.Close()
if err != nil {
s.log.Warnf("WS close error: %s", err)
}
s.log.Debug("Closed websocket")
s.disconnected = true
s.conn = nil
return err
}
//Send send a message
func (s *Socket) Send(msg []byte) error {
if s.conn == nil {
return nil
}
s.mutex.Lock()
defer s.mutex.Unlock()
return s.conn.WriteMessage(websocket.TextMessage, msg)
}