-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprotocol.go
85 lines (73 loc) · 1.81 KB
/
protocol.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
package main
import (
"bytes"
"encoding/binary"
"io"
"net"
log "github.com/nicholaskh/log4go"
)
const (
HEAD_LENGTH = 8
)
type Protocol struct {
net.Conn
app string
}
func NewProtocol(app string) *Protocol {
this := new(Protocol)
this.app = app
return this
}
func (this *Protocol) SetConn(conn net.Conn) {
this.Conn = conn
}
//len+appLength+app+payload
func (this *Protocol) Marshal(payload []byte) []byte {
buf := bytes.NewBuffer([]byte{})
tmpBuff := bytes.NewBuffer([]byte{})
binary.Write(buf, binary.BigEndian, int32(len(payload)))
binary.Write(tmpBuff, binary.BigEndian, int32(len(this.app)))
buf.Write(tmpBuff.Bytes())
buf.Write([]byte(this.app))
buf.Write(payload)
return buf.Bytes()
}
func (this *Protocol) Read() ([]byte, []byte, error) {
buf := make([]byte, HEAD_LENGTH)
err := this.ReadN(this.Conn, buf, HEAD_LENGTH)
if err != nil {
log.Error("[Protocol] Read data length error: %s", err.Error())
return []byte{}, []byte{}, err
}
//data length
b_buf := bytes.NewBuffer(buf[:4])
var dataLength int32
binary.Read(b_buf, binary.BigEndian, &dataLength)
//app length
var appLength int32
b_buf.Write(buf[4:8])
binary.Read(b_buf, binary.BigEndian, &appLength)
//app + data
payloadLength := int(dataLength + appLength)
payload := make([]byte, payloadLength)
err = this.ReadN(this.Conn, payload, payloadLength)
if err != nil && err != io.EOF {
log.Error("[Protocol] Read data error: %s", err.Error())
return []byte{}, []byte{}, err
}
return payload[:appLength], payload[appLength:payloadLength], nil
}
func (this *Protocol) ReadN(conn net.Conn, buf []byte, n int) error {
buffer := bytes.NewBuffer([]byte{})
for n > 0 {
b_buf := make([]byte, n)
readN, err := conn.Read(b_buf)
if err != nil {
return err
}
n -= readN
buffer.Write(b_buf)
}
copy(buf, buffer.Bytes())
return nil
}