Last active
August 15, 2018 03:30
-
-
Save bryant24/08f6941e4eaef93aa5a2542bff100c9e to your computer and use it in GitHub Desktop.
socket message pack & unpack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//通讯协议处理,主要处理封包和解包的过程 | |
package protocol | |
import ( | |
"bytes" | |
"encoding/binary" | |
) | |
const ( | |
ConstHeader = "secret" | |
ConstHeaderLength = 17 | |
ConstSaveDataLength = 4 | |
) | |
//封包 | |
func Packet(message []byte) []byte { | |
return append(append([]byte(ConstHeader), IntToBytes(len(message))...), message...) | |
} | |
//解包 | |
func Unpack(buffer []byte, readerChannel chan []byte) []byte { | |
length := len(buffer) | |
var i int | |
for i = 0; i < length; i = i + 1 { | |
if length < i + ConstHeaderLength + ConstSaveDataLength { | |
break | |
} | |
if string(buffer[i:i + ConstHeaderLength]) == ConstHeader { | |
messageLength := BytesToInt(buffer[i + ConstHeaderLength : i + ConstHeaderLength + ConstSaveDataLength]) | |
if length < i + ConstHeaderLength + ConstSaveDataLength + messageLength { | |
break | |
} | |
data := buffer[i + ConstHeaderLength + ConstSaveDataLength : i + ConstHeaderLength + ConstSaveDataLength + messageLength] | |
readerChannel <- data | |
i += ConstHeaderLength + ConstSaveDataLength + messageLength - 1 | |
} | |
} | |
if i == length { | |
return make([]byte, 0) | |
} | |
return buffer[i:] | |
} | |
//整形转换成字节 | |
func IntToBytes(n int) []byte { | |
x := int32(n) | |
bytesBuffer := bytes.NewBuffer([]byte{}) | |
binary.Write(bytesBuffer, binary.BigEndian, x) | |
return bytesBuffer.Bytes() | |
} | |
//字节转换成整形 | |
func BytesToInt(b []byte) int { | |
bytesBuffer := bytes.NewBuffer(b) | |
var x int32 | |
binary.Read(bytesBuffer, binary.BigEndian, &x) | |
return int(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment