forked from jcelliott/turnpike
-
Notifications
You must be signed in to change notification settings - Fork 3
/
websocket.go
77 lines (72 loc) · 1.79 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
76
77
package turnpike
import (
"fmt"
"github.com/gorilla/websocket"
)
type websocketPeer struct {
conn *websocket.Conn
serializer Serializer
messages chan Message
payloadType int
}
// NewWebsocketPeer connects to the websocket server at the specified url.
func NewWebsocketPeer(serialization Serialization, url, origin string) (Peer, error) {
switch serialization {
case JSON:
return newWebsocketPeer(url, jsonWebsocketProtocol, origin,
new(JSONSerializer), websocket.TextMessage,
)
case MSGPACK:
return newWebsocketPeer(url, msgpackWebsocketProtocol, origin,
new(MessagePackSerializer), websocket.BinaryMessage,
)
default:
return nil, fmt.Errorf("Unsupported serialization: %s", serialization)
}
}
func newWebsocketPeer(url, protocol, origin string, serializer Serializer, payloadType int) (Peer, error) {
dialer := websocket.Dialer{
Subprotocols: []string{protocol},
}
conn, _, err := dialer.Dial(url, nil)
if err != nil {
return nil, err
}
ep := &websocketPeer{
conn: conn,
messages: make(chan Message, 10),
serializer: serializer,
payloadType: payloadType,
}
go func() {
for {
// TODO: use conn.NextMessage() and stream
// TODO: do something different based on binary/text frames
if _, b, err := conn.ReadMessage(); err != nil {
conn.Close()
break
} else {
msg, err := serializer.Deserialize(b)
if err != nil {
// TODO: handle error
} else {
ep.messages <- msg
}
}
}
}()
return ep, nil
}
func (ep *websocketPeer) Send(msg Message) error {
b, err := ep.serializer.Serialize(msg)
if err != nil {
return err
}
return ep.conn.WriteMessage(ep.payloadType, b)
}
func (ep *websocketPeer) Receive() <-chan Message {
return ep.messages
}
func (ep *websocketPeer) Close() error {
return ep.conn.Close()
}