-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
121 lines (103 loc) · 2.02 KB
/
Copy pathnode.go
File metadata and controls
121 lines (103 loc) · 2.02 KB
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
package wsrpc
import (
"log"
"time"
"sync"
"errors"
"golang.org/x/net/websocket"
)
type connSafe struct {
ch chan *Conn
}
func (cs *connSafe) get() (c *Conn) {
c = <-cs.ch
cs.ch <- c
return
}
func (cs *connSafe) set(c *Conn) {
<-cs.ch
cs.ch <- c
}
func newConnSafe() *connSafe {
ch := make(chan *Conn, 1)
ch <- nil
return &connSafe{ch}
}
type Node struct {
conn *connSafe
Url string
Origin string
srv *service
connected sync.WaitGroup
reconnect uint16
}
func (n *Node) dial() (c *wsConn, err error) {
var ws *websocket.Conn
ws, err = websocket.Dial(n.Url, "", n.Origin)
if err != nil { return }
mux := n.conn.get()
c = wrapConn(ws, mux.Header)
err = c.validate(n.srv)
if err != nil { panic(err) }
go c.serve(mux)
return
}
func (n *Node) connect() (err error) {
var ws *wsConn
mux := newConn(n.srv, n.dial)
n.conn.set(mux)
ws, err = mux.pool.Get()
if err != nil { return }
mux.init(ws.id, ws.header)
mux.pool.Put(ws)
n.connected.Done()
log.Printf("[INFO] Connected to %s\n", n.Url)
return
}
func (n *Node) WaitConnected() {
n.connected.Wait()
}
func (n *Node) GetConnection() *Conn {
n.connected.Wait()
return n.conn.get()
}
// Enable reconnection every <elapse> seconds until successful
func (n *Node) SetReconnect(elapse uint16) {
n.reconnect = elapse
}
func (n *Node) SetMaxSocket(max uint8) {
n.srv.maxSocket(max)
}
func (n *Node) Serve() {
for {
err := n.connect()
if err != nil {
n.conn.set(nil)
log.Printf("[ERROR] %s\n", err)
if n.reconnect == 0 { break }
time.Sleep(time.Duration(n.reconnect) *time.Second)
} else {
n.conn.get().serve()
// Lost connection
n.conn.set(nil)
if n.reconnect == 0 { break }
n.connected.Add(1)
}
}
}
func (n *Node) Close() error {
if c := n.conn.get(); c != nil {
c.Close()
return nil
}
return errors.New("Node is not connected.")
}
func NewNode(url string, s Service) *Node {
srv := newService()
if s != nil {
srv.register(s)
}
n := Node{Url: url, Origin: url, srv: srv, conn: newConnSafe()}
n.connected.Add(1)
return &n
}