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.

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