This is a creation in Article, where the information may have evolved or changed.
Protocolbuff is an open-source serialization protocol from Google that almost supports all the mainstream languages on the market. The network transport protocol used as a server or server or a client-server is no more appropriate. Simply write a demo.
Project structure:
ProtocolBuff ----Makefile ----src ----github.com/golang/protobuf ----main ----protocol
Configuration Protocol:
Protocol/protocol.proto
package protocol;enum ItemType{ USERITEM = 1; EQUIPMENT = 2;};message ItemInfo{ optional int32 ID = 1; optional int32 Type = 2; optional string Name = 3; optional int32 Amount = 4;};
Executes PROTOC--go_out=./Protocol.proto automatically generates PROTOCOL.PB.GO, generating the directory as the current directory. PROTOC supports the generation of multiple languages, with protoc-h viewing.
Main/main.go
package mainimport ( "github.com/golang/protobuf/proto" "fmt" "protocol")func main() { item := protocol.ItemInfo{ ID : proto.Int32(10), Type : proto.Int32(1), Name : proto.String("item_0"), Amount: proto.Int32(99), } data := EncodeMsg(&item)//封包 fmt.Printf("Encode Data %v \n", data) res := DecodeMsg(data)//解包 fmt.Printf("Decode Data %v \n", res.String())}func EncodeMsg(pb proto.Message) []byte{ data, err := proto.Marshal(pb) if err != nil{ fmt.Errorf("%v \n",err.Error()) } return data}func DecodeMsg(data []byte) (result protocol.ItemInfo){ proto.Unmarshal(data, &result) return}
Makefile
GOPATH := $(shell pwd)all: GOPATH=${GOPATH} go install main
After make, the executable file is generated in the Bin directory, main, and the results are executed:
Encode Data [8 10 16 1 26 6 105 116 101 109 95 48 32 99]
Decode Data id:10 type:1 Name: "Item_0" amount:99