Package Protocol Import ("bytes" "Encoding/binary") Const(Constheader= "Jackluo"Constheaderlength= 7Constsavedatalength= 4) //Sealing Packagefunc Packet (message []byte) []byte {returnAppend (Append ([]byte (Constheader), inttobytes (len (message)), message ...))} //UnpackingFuncUnpack(Buffer []byte,Readerchannel Chan []byte] []byte {length:=len (buffer)varI int fori = 0; i < length; i = i + 1 { ifLength < i+constheaderlength+Constsavedatalength { Break } if string(Buffer[i:i+constheaderlength]) = =Constheader {messagelength: = Bytestoint (buffer[i+constheaderlength:i+constheaderlength+Constsavedatalength]) ifLength < i+constheaderlength+constsavedatalength+Messagelength { Break} data: = buffer[i+constheaderlength+constsavedatalength:i+constheaderlength+constsavedatalength+Messagelength] Readerchannel<-data i+ = Constheaderlength + constsavedatalength + messageLength-1 } } ifi = =Length {returnMake ([]byte, 0) } returnBuffer[i:]} //shaping into bytesfunc inttobytes (n int) []byte {x:=int32 (N) bytesbuffer: = bytes.newbuffer ([]byte{}) binary. Write (Bytesbuffer, Binary. Bigendian,x)returnBytesbuffer.Bytes ()}//converting bytes into shapingfunc bytestoint (b []byte) int {Bytesbuffer: = bytes.Newbuffer (b)varx Int32 binary. Read (Bytesbuffer, Binary. Bigendian, &x)returnint (x)}
Package Mainimport ("FMT" "NET" "OS" "./protocol") Func main () {Netlisten, Err: = Net. Listen ("TCP", ": 9988") CheckError (err) defer Netlisten.Close ()Log("Waiting for Clients") for{conn, err: = Netlisten.Accept ()ifErr! =Nil {Continue } Log(Conn. Remoteaddr ().String(), "TCP Connect Success") Go handleconnection (conn)}}func handleconnection (Conn net.Conn) { //declares a temporary buffer that is used to store truncated dataTmpbuffer: = Make ([]byte, 0) //declares a pipeline to receive the unpacked dataReaderchannel: = Make (chan []byte, 16) Go Reader (readerchannel) buffer: = Make ([]byte, 1024) for{n, ERR: = conn.Read (buffer)ifErr! =Nil {Log(Conn. Remoteaddr ().String(), "Connection error:",err)return }/*LOG (Conn. Remoteaddr (). String (), "Receive data length:", N) Log (Conn. Remoteaddr (). String (), "Receive data:", Buffer[:n]) LOG (Conn. Remoteaddr (). String (), "Receive data string:", String (Buffer[:n]))*/Tmpbuffer= protocol.Unpack(Append (Tmpbuffer, buffer[:n] ...),Readerchannel)}} Func Reader (Readerchannel Chan []byte) { for{select { CaseData: = <-readerchannel:Log(string(data))} }}funcLog(v ...Interface{}) {FMT. Println (v ...)} func checkerror (err error) {ifErr! =Nil {FMT.fprintf(OS. Stderr, "Fatal Error:%s", err.Error ()) OS.Exit(1) }}
Package main Import ("FMT" "NET" "OS" "Time" "./protocol") Func Sender (Conn net.Conn) { forI: = 0; I < 100; i++{words: = "{\" id\ ": 1,\" name\ ": \" golang\ ", \" message\ ": \" message\ "}"Conn. Write (protocol.Packet ([]byte (words))} FMT. PRINTLN ("Send Over")} func main () {server: = "127.0.0.1:9988"tcpaddr, Err: = Net. RESOLVETCPADDR ("TCP4",server)ifErr! =Nil {FMT.fprintf(OS. Stderr, "Fatal Error:%s", err.Error ()) OS.Exit(1)} conn, Err: = Net. DIALTCP ("TCP", nil,tcpaddr)ifErr! =Nil {FMT.fprintf(OS. Stderr, "Fatal Error:%s", err.Error ()) OS.Exit(1)} Defer conn.Close () fmt. PRINTLN ("Connect Success") Go Sender (conn) for { Time.Sleep(1 * 1e9) }}
Golang Custom Packet Protocol (RPM)