WebCodec.go 689 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package base
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "github.com/panjf2000/gnet"
  6. log "github.com/sirupsen/logrus"
  7. )
  8. type WebTcpCodec struct {
  9. }
  10. func (pc *TcpCodec) WebEncode(c gnet.Conn, buf []byte) (out []byte, err error) {
  11. rs := make([]byte, 4)
  12. binary.LittleEndian.PutUint32(rs, uint32(len(buf)))
  13. out = bytes.Join([][]byte{rs, buf}, []byte(""))
  14. return
  15. }
  16. func (pc *TcpCodec) WebDecode(c gnet.Conn) (out []byte, err error) {
  17. log.Info("收到了消息", c.Read())
  18. // c.AsyncWrite(out)
  19. rs, bs := c.ReadN(4)
  20. if rs != 4 {
  21. return
  22. }
  23. ts := int(binary.LittleEndian.Uint32(bs)) + rs
  24. size, buf := c.ReadN(ts)
  25. if size != ts {
  26. return
  27. }
  28. c.ShiftN(size)
  29. out = buf[4:]
  30. return
  31. }