package base import ( "bytes" "encoding/binary" "github.com/panjf2000/gnet" log "github.com/sirupsen/logrus" ) type WebTcpCodec struct { } func (pc *TcpCodec) WebEncode(c gnet.Conn, buf []byte) (out []byte, err error) { rs := make([]byte, 4) binary.LittleEndian.PutUint32(rs, uint32(len(buf))) out = bytes.Join([][]byte{rs, buf}, []byte("")) return } func (pc *TcpCodec) WebDecode(c gnet.Conn) (out []byte, err error) { log.Info("收到了消息", c.Read()) // c.AsyncWrite(out) rs, bs := c.ReadN(4) if rs != 4 { return } ts := int(binary.LittleEndian.Uint32(bs)) + rs size, buf := c.ReadN(ts) if size != ts { return } c.ShiftN(size) out = buf[4:] return }