1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import ( "encoding/binary" "errors" "io" "net" )
type MsgPack struct { maxMsgLen uint16 }
func NewMsgPack() *MsgPack { p := new(MsgPack) p.maxMsgLen = 4096
return p }
func (c *MsgPack) ReadPack(session net.Conn) ([]byte, error) { var headData []byte = make([]byte, 2) if _, err := io.ReadFull(session, headData); err != nil { return nil, err } msgLen := uint16(binary.LittleEndian.Uint16(headData)) if msgLen > c.maxMsgLen { return nil, errors.New("message too long") }
msgData := make([]byte, msgLen) if _, err := io.ReadFull(session, msgData); err != nil { return nil, err }
return msgData, nil }
func (p *MsgPack) WritePack(conn net.Conn, args ...[]byte) error { var msgLen uint16 for i := 0; i < len(args); i++ { msgLen += uint16(len(args[i])) }
if msgLen > p.maxMsgLen { return errors.New("message too long") }
msg := make([]byte, uint32(2)+uint32(msgLen))
binary.LittleEndian.PutUint16(msg, uint16(msgLen))
l := 2 for i := 0; i < len(args); i++ { copy(msg[l:], args[i]) l += len(args[i]) }
conn.Write(msg)
return nil }
|