mihomo/transport/ssr/protocol/stream.go

51 lines
841 B
Go
Raw Normal View History

package protocol
import (
"bytes"
"net"
2023-11-03 21:01:45 +08:00
"github.com/metacubex/mihomo/common/pool"
)
type Conn struct {
net.Conn
Protocol
decoded bytes.Buffer
underDecoded bytes.Buffer
}
func (c *Conn) Read(b []byte) (int, error) {
if c.decoded.Len() > 0 {
return c.decoded.Read(b)
}
buf := pool.Get(pool.RelayBufferSize)
defer pool.Put(buf)
n, err := c.Conn.Read(buf)
if err != nil {
return 0, err
}
c.underDecoded.Write(buf[:n])
err = c.Decode(&c.decoded, &c.underDecoded)
if err != nil {
return 0, err
}
n, _ = c.decoded.Read(b)
return n, nil
}
func (c *Conn) Write(b []byte) (int, error) {
bLength := len(b)
2021-09-20 21:02:18 +08:00
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
err := c.Encode(buf, b)
if err != nil {
return 0, err
}
_, err = c.Conn.Write(buf.Bytes())
if err != nil {
return 0, err
}
return bLength, nil
}