codec.go 872 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package remote_manager
  2. import (
  3. "bytes"
  4. "errors"
  5. "github.com/panjf2000/gnet/v2"
  6. )
  7. type codec struct {
  8. buf bytes.Buffer
  9. }
  10. func (w *codec) Decode(c gnet.Conn) ([][]byte, error) {
  11. size := c.InboundBuffered()
  12. buf := make([]byte, size)
  13. read, err := c.Read(buf)
  14. if err != nil {
  15. return nil, err
  16. }
  17. if read < size {
  18. return nil, errors.New("read less than size")
  19. }
  20. return w.getLines(buf), nil
  21. }
  22. func (w *codec) getLines(data []byte) [][]byte {
  23. // write to buffer
  24. w.buf.Write(data)
  25. // read line by line, split by \n, remaining data will be kept in buffer
  26. lines := bytes.Split(w.buf.Bytes(), []byte("\n"))
  27. w.buf.Reset()
  28. // if last line is not complete, keep it in buffer
  29. if len(lines[len(lines)-1]) != 0 {
  30. w.buf.Write(lines[len(lines)-1])
  31. lines = lines[:len(lines)-1]
  32. } else if len(lines) > 0 {
  33. lines = lines[:len(lines)-1]
  34. }
  35. return lines
  36. }