-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwebsocket.go
75 lines (66 loc) · 1.21 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
package main
import (
"sync"
"time"
"github.com/hectorchu/gonano/rpc"
"github.com/hectorchu/gonano/websocket"
)
type wsClientType struct {
m sync.Mutex
key int
sub []wsClientSub
}
type wsClientSub struct {
key int
f func(*rpc.Block)
}
var wsClient = wsClientType{}
func init() {
for _, url := range []string{
"wss://gonano.dev/ws",
"wss://ws.mynano.ninja",
"wss://ws.powernode.cc",
"wss://rainstorm.city/websocket",
} {
ws := &websocket.Client{URL: url}
if ws.Connect() == nil {
go wsClient.loop(ws)
return
}
}
}
func (c *wsClientType) subscribe(f func(*rpc.Block)) (key int) {
c.m.Lock()
key = c.key
c.key++
c.sub = append(c.sub, wsClientSub{key: key, f: f})
c.m.Unlock()
return
}
func (c *wsClientType) unsubscribe(key int) {
c.m.Lock()
for i, sub := range c.sub {
if sub.key == key {
c.sub = append(c.sub[:i], c.sub[i+1:]...)
break
}
}
c.m.Unlock()
}
func (c *wsClientType) loop(ws *websocket.Client) {
for {
switch m := (<-ws.Messages).(type) {
case *websocket.Confirmation:
c.m.Lock()
for _, sub := range c.sub {
sub.f(m.Block)
}
c.m.Unlock()
case error:
ws.Close()
for ws.Connect() != nil {
time.Sleep(10 * time.Second)
}
}
}
}