github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/transport/ssr/protocol/packet.go (about)

     1  package protocol
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/laof/lite-speed-test/common/pool"
     7  )
     8  
     9  type PacketConn struct {
    10  	net.PacketConn
    11  	Protocol
    12  }
    13  
    14  func (c *PacketConn) WriteTo(b []byte, addr net.Addr) (int, error) {
    15  	buf := pool.GetBuffer()
    16  	defer pool.PutBuffer(buf)
    17  	err := c.EncodePacket(buf, b)
    18  	if err != nil {
    19  		return 0, err
    20  	}
    21  	_, err = c.PacketConn.WriteTo(buf.Bytes(), addr)
    22  	return len(b), err
    23  }
    24  
    25  func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) {
    26  	n, addr, err := c.PacketConn.ReadFrom(b)
    27  	if err != nil {
    28  		return n, addr, err
    29  	}
    30  	decoded, err := c.DecodePacket(b[:n])
    31  	if err != nil {
    32  		return n, addr, err
    33  	}
    34  	copy(b, decoded)
    35  	return len(decoded), addr, nil
    36  }