This repository has been archived by the owner on Oct 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathprotocol.go
85 lines (75 loc) · 1.54 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 (
"io"
"bytes"
)
type HelloMessage struct {
Version string
UUID string
UserKey string
}
type EditSocketMessage struct {
MessageType string `json:"type"`
Url string `json:"url"`
}
const DELIMITER = "11~~~~~!!END!!~~~~~11"
var DELIMITERBUFFER = []byte(DELIMITER)
const BUFFER_SIZE = 4096
const PROTOCOL_VERSION = "1.0"
func ReadFrame(r io.Reader) (requestId byte, buffer []byte, err error) {
buffer = nil
requestIdBuffer := make([]byte, 1)
_, err = io.ReadFull(r, requestIdBuffer)
requestId = requestIdBuffer[0]
lengthBuffer := make([]byte, 2)
if err != nil {
return
}
_, err = io.ReadFull(r, lengthBuffer)
if err != nil {
return
}
length := BytesToInt(lengthBuffer)
buffer = make([]byte, length)
_, err = io.ReadFull(r, buffer)
if err != nil {
return
}
return
}
func WriteFrame(w io.Writer, requestId byte, buffer []byte) error {
_, err := w.Write([]byte{requestId})
if err != nil {
return err
}
_, err = w.Write(IntToBytes(len(buffer)))
if err != nil {
return err
}
totalWritten := 0
for totalWritten < len(buffer) {
n, err := w.Write(buffer[totalWritten:])
if err != nil {
return err
}
totalWritten += n
}
return err
}
func IsDelimiter(buffer []byte) bool {
if len(buffer) != len(DELIMITER) {
return false
} else {
return bytes.Equal(buffer, DELIMITERBUFFER)
}
return false
}
func IntToBytes(n int) []byte {
buf := make([]byte, 2)
buf[0] = byte(n / 256)
buf[1] = byte(n % 256)
return buf
}
func BytesToInt(buf []byte) int {
return int(buf[0]) * 256 + int(buf[1])
}