-
Notifications
You must be signed in to change notification settings - Fork 63
/
gowebsocket.go
200 lines (176 loc) · 5.13 KB
/
gowebsocket.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
package gowebsocket
import (
"github.com/gorilla/websocket"
"net/http"
"errors"
"crypto/tls"
"net/url"
"sync"
"github.com/sacOO7/go-logger"
"reflect"
"time"
)
type Empty struct {
}
var logger = logging.GetLogger(reflect.TypeOf(Empty{}).PkgPath()).SetLevel(logging.OFF)
func (socket Socket) EnableLogging() {
logger.SetLevel(logging.TRACE)
}
func (socket Socket) GetLogger() logging.Logger {
return logger;
}
type Socket struct {
Conn *websocket.Conn
WebsocketDialer *websocket.Dialer
Url string
ConnectionOptions ConnectionOptions
RequestHeader http.Header
OnConnected func(socket Socket)
OnTextMessage func(message string, socket Socket)
OnBinaryMessage func(data [] byte, socket Socket)
OnConnectError func(err error, socket Socket)
OnDisconnected func(err error, socket Socket)
OnPingReceived func(data string, socket Socket)
OnPongReceived func(data string, socket Socket)
IsConnected bool
Timeout time.Duration
sendMu *sync.Mutex // Prevent "concurrent write to websocket connection"
receiveMu *sync.Mutex
}
type ConnectionOptions struct {
UseCompression bool
UseSSL bool
Proxy func(*http.Request) (*url.URL, error)
Subprotocols [] string
}
// todo Yet to be done
type ReconnectionOptions struct {
}
func New(url string) Socket {
return Socket{
Url: url,
RequestHeader: http.Header{},
ConnectionOptions: ConnectionOptions{
UseCompression: false,
UseSSL: true,
},
WebsocketDialer: &websocket.Dialer{},
Timeout: 0,
sendMu: &sync.Mutex{},
receiveMu: &sync.Mutex{},
}
}
func (socket *Socket) setConnectionOptions() {
socket.WebsocketDialer.EnableCompression = socket.ConnectionOptions.UseCompression
socket.WebsocketDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: socket.ConnectionOptions.UseSSL}
socket.WebsocketDialer.Proxy = socket.ConnectionOptions.Proxy
socket.WebsocketDialer.Subprotocols = socket.ConnectionOptions.Subprotocols
}
func (socket *Socket) Connect() {
var err error;
var resp *http.Response
socket.setConnectionOptions()
socket.Conn, resp, err = socket.WebsocketDialer.Dial(socket.Url, socket.RequestHeader)
if err != nil {
logger.Error.Println("Error while connecting to server ", err)
if resp != nil {
logger.Error.Println("HTTP Response %d status: %s", resp.StatusCode, resp.Status)
}
socket.IsConnected = false
if socket.OnConnectError != nil {
socket.OnConnectError(err, *socket)
}
return
}
logger.Info.Println("Connected to server")
if socket.OnConnected != nil {
socket.IsConnected = true
socket.OnConnected(*socket)
}
defaultPingHandler := socket.Conn.PingHandler()
socket.Conn.SetPingHandler(func(appData string) error {
logger.Trace.Println("Received PING from server")
if socket.OnPingReceived != nil {
socket.OnPingReceived(appData, *socket)
}
return defaultPingHandler(appData)
})
defaultPongHandler := socket.Conn.PongHandler()
socket.Conn.SetPongHandler(func(appData string) error {
logger.Trace.Println("Received PONG from server")
if socket.OnPongReceived != nil {
socket.OnPongReceived(appData, *socket)
}
return defaultPongHandler(appData)
})
defaultCloseHandler := socket.Conn.CloseHandler()
socket.Conn.SetCloseHandler(func(code int, text string) error {
result := defaultCloseHandler(code, text)
logger.Warning.Println("Disconnected from server ", result)
if socket.OnDisconnected != nil {
socket.IsConnected = false
socket.OnDisconnected(errors.New(text), *socket)
}
return result
})
go func() {
for {
socket.receiveMu.Lock()
if socket.Timeout != 0 {
socket.Conn.SetReadDeadline(time.Now().Add(socket.Timeout))
}
messageType, message, err := socket.Conn.ReadMessage()
socket.receiveMu.Unlock()
if err != nil {
logger.Error.Println("read:", err)
if socket.OnDisconnected != nil {
socket.IsConnected = false
socket.OnDisconnected(err, *socket)
}
return
}
logger.Info.Println("recv: %s", message)
switch messageType {
case websocket.TextMessage:
if socket.OnTextMessage != nil {
socket.OnTextMessage(string(message), *socket)
}
case websocket.BinaryMessage:
if socket.OnBinaryMessage != nil {
socket.OnBinaryMessage(message, *socket)
}
}
}
}()
}
func (socket *Socket) SendText(message string) {
err := socket.send(websocket.TextMessage, [] byte (message))
if err != nil {
logger.Error.Println("write:", err)
return
}
}
func (socket *Socket) SendBinary(data [] byte) {
err := socket.send(websocket.BinaryMessage, data)
if err != nil {
logger.Error.Println("write:", err)
return
}
}
func (socket *Socket) send(messageType int, data [] byte) error {
socket.sendMu.Lock()
err := socket.Conn.WriteMessage(messageType, data)
socket.sendMu.Unlock()
return err
}
func (socket *Socket) Close() {
err := socket.send(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
logger.Error.Println("write close:", err)
}
socket.Conn.Close()
if socket.OnDisconnected != nil {
socket.IsConnected = false
socket.OnDisconnected(err, *socket)
}
}