forked from icedream/go-stagelinq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
message_connection.go
94 lines (79 loc) · 1.99 KB
/
message_connection.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
package stagelinq
import (
"bufio"
"bytes"
"net"
"reflect"
)
type messageSet struct {
messages []reflect.Type
}
func newDeviceConnMessageSet(messageObjects []message) *messageSet {
messages := make([]reflect.Type, len(messageObjects))
for i, messageObject := range messageObjects {
// .Elem() because type will be a pointer-to-type but we want to create instances of the type itself later
messages[i] = reflect.TypeOf(messageObject).Elem()
}
return &messageSet{messages}
}
func (ms *messageSet) Messages() []reflect.Type {
return ms.messages
}
type messageConnection struct {
conn net.Conn
bufferedReader *bufio.Reader
expectedMessages *messageSet
}
func newMessageConnection(conn net.Conn, expectedMessages *messageSet) *messageConnection {
if conn == nil {
panic("conn must not be nil")
}
if expectedMessages == nil {
panic("expectedMessages must not be nil")
}
if len(expectedMessages.Messages()) <= 0 {
panic("expectedMessages must not be empty")
}
return &messageConnection{
conn: conn,
bufferedReader: bufio.NewReader(conn),
expectedMessages: expectedMessages,
}
}
func (s *messageConnection) WriteMessage(msg message) (err error) {
buf := new(bytes.Buffer)
// write message parts into buffer
if err = msg.writeTo(buf); err != nil {
return
}
// write the whole thing out as one message to the device
_, err = s.conn.Write(buf.Bytes())
// if err == nil {
// log.Printf("SEND: %s", spew.Sdump(msg))
// }
return
}
func (s *messageConnection) ReadMessage() (msg message, err error) {
var targetMsg message
var ok bool
for _, messageType := range s.expectedMessages.Messages() {
targetMsg = reflect.New(messageType).Interface().(message)
ok, err = targetMsg.checkMatch(s.bufferedReader)
if err != nil {
return
}
if ok {
break
}
}
if !ok {
err = ErrInvalidMessageReceived
return
}
err = targetMsg.readFrom(s.bufferedReader)
if err == nil {
msg = targetMsg
// log.Printf("RECV: %s", spew.Sdump(msg))
}
return
}