赞
踩
package main import ( "encoding/binary" "encoding/json" "fmt" "io" "net" ) type REQ struct { Code int64 // Content string // 发送的内容 } type RESP struct { Content string // 发送的内容 Code int64 // } func RecvPck(conn net.Conn) (*REQ, error) { var sizeBuffer = make([]byte, 2) _, err := io.ReadFull(conn, sizeBuffer) if err != nil { fmt.Println("read head err") return nil, err } // 用大端格式读取Size size := binary.BigEndian.Uint16(sizeBuffer) //L fmt.Printf("L=%d\n", size) // 分配包体大小 body := make([]byte, size) // 读取包体数据 _, err = io.ReadFull(conn, body) //body = T+V if err != nil { fmt.Println("read body err") return nil, err } T := binary.LittleEndian.Uint16(body[:2]) fmt.Printf("T=%d\n", T) req := &REQ{ } err = json.Unmarshal(body[2:], req) if err != nil { return nil, err } fmt.Printf("V=%+v\n", req) return req, nil } func SendPck(conn net.Conn, T uint16, req string) error { resp := &RESP{ Code: int64(T), Content: req, } json_content, _ := json.Marshal(resp) L := len(string(json_content)) + 2 fmt.Printf("send L=%d\n", L) //T := 1 buffer := make([]byte, L+2) // 将包体长度写入缓冲 binary.BigEndian.PutUint16(buffer, uint16(L)) tmp := make(
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。