mihomo/transport/ssr/protocol/packet.go

55 lines
1 KiB
Go
Raw Normal View History

package protocol
import (
"net"
2023-11-03 21:01:45 +08:00
N "github.com/metacubex/mihomo/common/net"
"github.com/metacubex/mihomo/common/pool"
)
type PacketConn struct {
2023-05-28 22:51:26 +08:00
N.EnhancePacketConn
Protocol
}
func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
2021-09-20 21:02:18 +08:00
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
err := c.EncodePacket(buf, b)
if err != nil {
return 0, err
}
2023-05-28 22:51:26 +08:00
_, err = c.EnhancePacketConn.WriteTo(buf.Bytes(), addr)
return len(b), err
}
func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
2023-05-28 22:51:26 +08:00
n, addr, err := c.EnhancePacketConn.ReadFrom(b)
if err != nil {
return n, addr, err
}
decoded, err := c.DecodePacket(b[:n])
if err != nil {
return n, addr, err
}
copy(b, decoded)
return len(decoded), addr, nil
}
2023-05-28 22:51:26 +08:00
func (c *PacketConn) WaitReadFrom() (data []byte, put func(), addr net.Addr, err error) {
data, put, addr, err = c.EnhancePacketConn.WaitReadFrom()
if err != nil {
return
}
data, err = c.DecodePacket(data)
if err != nil {
if put != nil {
put()
}
data = nil
put = nil
return
}
return
}