1.构建数据包过程
package protocol import ( "bufio" "bytes" "encoding/binary" "fmt" ) //构建网络中数据包格式 func Encode (message string ) []byte { var length = int32(len(message)) var pkg = new(bytes.Buffer) err:=binary.Write(pkg,binary.LittleEndian,length)//前四个字节 if err != nil { fmt.Println("build pkg is error") return nil } err=binary.Write(pkg,binary.LittleEndian,[]byte(message)) if err != nil { return nil } return pkg.Bytes() } //解包过程 func Decode( reader *bufio.Reader) string { lengthBytes,_:= reader.Peek(4)//前4个字节数据 lengthBuff:=bytes.NewBuffer(lengthBytes) var length int32 binary.Read(lengthBuff,binary.LittleEndian,&length) //if int32(reader.Buffered()) < length +4 { // return nil //} pack:=make([]byte, int(4+length)) reader.Read(pack) return string(pack[4:]) }
1.服务端
package main import ( "bufio" "fmt" "net" "protocol" ) func process(conn net.Conn){ defer conn.Close() reader:=bufio.NewReader(conn) for { msg:= protocol.Decode(reader) fmt.Printf("%v\n",msg) } } func main(){ listener,err:=net.Listen("tcp","127.0.0.1:8890") if err != nil { fmt.Println("start server is erros") return } for { conn,_:= listener.Accept() go process(conn) } defer listener.Close() }
2.客户端
package main import ( "log" "net" "protocol" "time" ) func main(){ conn,err:=net.Dial("tcp","127.0.0.1:8890") if err != nil { log.Fatal("is error") return } str:="hello word你好" for i:=0;i<10;i++ { bytes:= protocol.Encode(str) conn.Write(bytes) time.Sleep(time.Second) } }