English | 简体中文
tcpack is an application protocol based on TCP to Pack and Unpack bytes stream in go (or 'golang' for search engine friendliness) program.
As we all know, TCP is a transport layer protocol oriented to byte streams. Its data transmission has no clear boundaries, so the data read by the application layer may contain multiple requests and cannot be processed.
tcpack is to solve this problem by encapsulating the request data into a message, packaging it when sending and unpacking it when receiving.
This library provides a packager which support Pack and Unpack.
- To install the tcpack package, you first need to have Go installed, then you can use the command below to add
tcpack
as a dependency in your Go program.
go get -u github.com/lim-yoona/tcpack
- Import it in your code:
import "github.com/lim-yoona/tcpack"
package main
import "github.com/lim-yoona/tcpack"
func main() {
// Create a packager
mp := tcpack.NewMsgPack(8, tcpConn)
// Pack a message
msg := tcpack.NewMessage(0, uint32(len([]byte(data))), []byte(data))
msgByte, err := mp.Pack(msg)
num, err := tcpConn.Write(msgByte)
// Unpack a message
msg, err := mp.Unpack()
}
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
// Create a packager
mp := tcpack.NewMsgPack(8, tcpConn)
// data JSON Marshal
data := &Person{
Name: "jack",
Age: 20,
}
dataJSON, _ := json.Marshal(data)
// Pack a message
msgSend := tcpack.NewMessage(0, uint32(len(dataJSON)), dataJSON)
msgSendByte, _ := mpClient.Pack(msgSend)
num, err := tcpConn.Write(msgSendByte)
// Unpack a message
msgRsv, err := mp.Unpack()
// JSON UnMarshal
var dataRsv Person
json.Unmarshal(msgRsv.GetMsgData(), &dataRsv)
Here are some Examples.