You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.8 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package znet
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "github.com/aceld/zinx/utils"
  7. "github.com/aceld/zinx/ziface"
  8. )
  9. //DataPack 封包拆包类实例,暂时不需要成员
  10. type DataPack struct{}
  11. //NewDataPack 封包拆包实例初始化方法
  12. func NewDataPack() *DataPack {
  13. return &DataPack{}
  14. }
  15. //GetHeadLen 获取包头长度方法
  16. func (dp *DataPack) GetHeadLen() uint32 {
  17. //ID uint32(4字节) + DataLen uint32(4字节)
  18. return 8
  19. }
  20. //Pack 封包方法(压缩数据)
  21. func (dp *DataPack) Pack(msg ziface.IMessage) ([]byte, error) {
  22. //创建一个存放bytes字节的缓冲
  23. dataBuff := bytes.NewBuffer([]byte{})
  24. //写dataLen
  25. if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetDataLen()); err != nil {
  26. return nil, err
  27. }
  28. //写msgID
  29. if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetMsgID()); err != nil {
  30. return nil, err
  31. }
  32. //写data数据
  33. if err := binary.Write(dataBuff, binary.LittleEndian, msg.GetData()); err != nil {
  34. return nil, err
  35. }
  36. return dataBuff.Bytes(), nil
  37. }
  38. //Unpack 拆包方法(解压数据)
  39. func (dp *DataPack) Unpack(binaryData []byte) (ziface.IMessage, error) {
  40. //创建一个从输入二进制数据的ioReader
  41. dataBuff := bytes.NewReader(binaryData)
  42. //只解压head的信息,得到dataLen和msgID
  43. msg := &Message{}
  44. //读dataLen
  45. if err := binary.Read(dataBuff, binary.LittleEndian, &msg.DataLen); err != nil {
  46. return nil, err
  47. }
  48. //读msgID
  49. if err := binary.Read(dataBuff, binary.LittleEndian, &msg.ID); err != nil {
  50. return nil, err
  51. }
  52. //判断dataLen的长度是否超出我们允许的最大包长度
  53. if utils.GlobalObject.MaxPacketSize > 0 && msg.DataLen > utils.GlobalObject.MaxPacketSize {
  54. return nil, errors.New("too large msg data received")
  55. }
  56. //这里只需要把head的数据拆包出来就可以了,然后再通过head的长度,再从conn读取一次数据
  57. return msg, nil
  58. }