share_udp_conn.go 804 B

123456789101112131415161718192021222324252627282930313233
  1. package p2p
  2. import (
  3. "blockchain-go/p2p/discover"
  4. "errors"
  5. "net"
  6. )
  7. // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns
  8. // messages that were found unprocessable and sent to the unhandled channel by the primary listener.
  9. type sharedUDPConn struct {
  10. *net.UDPConn
  11. unhandled chan discover.ReadPacket
  12. }
  13. // ReadFromUDP implements discover.UDPConn
  14. func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
  15. packet, ok := <-s.unhandled
  16. if !ok {
  17. return 0, nil, errors.New("connection was closed")
  18. }
  19. l := len(packet.Data)
  20. if l > len(b) {
  21. l = len(b)
  22. }
  23. copy(b[:l], packet.Data[:l])
  24. return l, packet.Addr, nil
  25. }
  26. // Close implements discover.UDPConn
  27. func (s *sharedUDPConn) Close() error {
  28. return nil
  29. }