forked from simon-whitehead/relayr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket-transport.go
118 lines (101 loc) · 2.16 KB
/
websocket-transport.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
package relayr
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gorilla/websocket"
)
type connection struct {
ws *websocket.Conn
out chan []byte
c *webSocketTransport
id string
e *Exchange
}
type webSocketTransport struct {
connections map[string]*connection
connected chan *connection
disconnected chan *connection
e *Exchange
}
type webSocketClientMessage struct {
Server bool `json:"S"`
Relay string `json:"R"`
Method string `json:"M"`
Arguments []interface{} `json:"A"`
ConnectionID string `json:"C"`
}
func newWebSocketTransport(e *Exchange) *webSocketTransport {
c := &webSocketTransport{
connected: make(chan *connection),
disconnected: make(chan *connection),
connections: make(map[string]*connection),
e: e,
}
go c.listen()
return c
}
func (c *webSocketTransport) listen() {
for {
select {
case conn := <-c.connected:
c.connections[conn.id] = conn
case conn := <-c.disconnected:
if _, ok := c.connections[conn.id]; ok {
c.e.removeFromAllGroups(conn.id)
delete(c.connections, conn.id)
close(conn.out)
}
}
}
}
func (c *webSocketTransport) CallClientFunction(relay *Relay, fn string, args ...interface{}) {
buff := &bytes.Buffer{}
encoder := json.NewEncoder(buff)
encoder.Encode(struct {
R string
M string
A []interface{}
}{
relay.Name,
fn,
args,
})
o := c.connections[relay.ConnectionID]
if o != nil {
o.out <- buff.Bytes()
}
}
func (c *connection) read() {
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
break
}
var m webSocketClientMessage
err = json.Unmarshal(message, &m)
if err != nil {
fmt.Println("ERR:", err)
continue
}
relay := c.e.getRelayByName(m.Relay, m.ConnectionID)
if m.Server {
err := c.e.callRelayMethod(relay, m.Method, m.Arguments...)
if err != nil {
fmt.Println("ERR:", err)
}
} else {
c.c.CallClientFunction(relay, m.Method, m.Arguments)
}
}
c.ws.Close()
}
func (c *connection) write() {
for message := range c.out {
err := c.ws.WriteMessage(websocket.TextMessage, message)
if err != nil {
break
}
}
c.ws.Close()
}