Golang Custom Packet Protocol (RPM)

Source: Internet
Author: User
Tags unpack

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.