github.com/haraldrudell/parl@v0.4.176/pnet/tcp-listener.go (about)

     1  /*
     2  © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pnet
     7  
     8  import (
     9  	"net"
    10  )
    11  
    12  // TCPListener wraps [net.TCPListener]
    13  //   - TCPListener provides:
    14  //   - — thread-safe methods from [TCPListener] and [SocketListener]
    15  //   - — promoted methods from [net.TCPListener]
    16  //   - — all errors via unbound error channel
    17  //   - — thread-safe state-handling for integrity
    18  //   - — idempotent panic-free awaitable thread-safe [TCPListener.Close]
    19  //   - — netip addresses
    20  //   - — panic-handled handler connection threads receiving [*net.TCPConn]
    21  //   - — awaitable Close and handler completion
    22  type TCPListener struct {
    23  	// the TCP IPv4 or IPv6 listening socket promoting TCP-specific methods
    24  	*net.TCPListener
    25  	// connection-handler argument is *net.TCPConn
    26  	SocketListener[*net.TCPConn]
    27  }
    28  
    29  // NewTCPListener returns an object for receiving tcp connections
    30  //   - network is address family and type: NetworkTCP NetworkTCP4 NetworkTCP6, default IPv4
    31  //   - socket implementation is [net.TCPListener]
    32  //   - [SocketListener.Ch] returns a real-time unbound error channel or
    33  //   - [SocketListener.Err] returns any errors appended into a single error
    34  //   - [TCPListener.Close] is idempotent panic-free awaitable thread-safe
    35  //   - [SocketListener.WaitCh]: channel closing on Close complete
    36  //   - [SocketListener.Listen]: starts connection listening
    37  //   - [SocketListener.AddrPort]: returns near socket address on successful listen
    38  //   - [SocketListener.AcceptConnections]: provides connections to handler function until Close is invoked
    39  //
    40  // Usage:
    41  //
    42  //	var socket = pnet.NewTCPListener()
    43  //	if err = r.socket.Listen("1.2.3.4:1234"); err != nil {
    44  //		return // listen failed
    45  //	}
    46  //	defer parl.Close(&r.socket, &err)
    47  //	println(socket.AddrPort().String()) // “127.0.0.1:1122”
    48  func NewTCPListener(network ...Network) (socket *TCPListener) {
    49  	var addressType Network
    50  	if len(network) > 0 {
    51  		addressType = network[0]
    52  	} else {
    53  		addressType = NetworkTCP4
    54  	}
    55  
    56  	var listener net.TCPListener
    57  	return &TCPListener{
    58  		TCPListener:    &listener,
    59  		SocketListener: *NewSocketListener[*net.TCPConn](&listener, addressType, TransportTCP),
    60  	}
    61  }
    62  
    63  // - idempotent panic-free awaitable Close
    64  func (s *TCPListener) Close() (err error) {
    65  	return s.SocketListener.Close()
    66  }