github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/network/tcp_listener.go (about)

     1  package network
     2  
     3  import (
     4  	"github.com/15mga/kiwi"
     5  	"net"
     6  
     7  	"github.com/15mga/kiwi/util"
     8  )
     9  
    10  func NewTcpListener(addr string, onConn func(conn net.Conn)) kiwi.IListener {
    11  	return &tcpListener{
    12  		addr:   addr,
    13  		onConn: onConn,
    14  	}
    15  }
    16  
    17  type tcpListener struct {
    18  	addr     string
    19  	listener *net.TCPListener
    20  	onConn   func(conn net.Conn)
    21  }
    22  
    23  func (l *tcpListener) Addr() string {
    24  	return l.addr
    25  }
    26  
    27  func (l *tcpListener) Port() int {
    28  	port, _ := util.ParseAddrPort(l.listener.Addr().String())
    29  	return port
    30  }
    31  
    32  func (l *tcpListener) Start() *util.Err {
    33  	addr, err := net.ResolveTCPAddr("tcp", l.addr)
    34  	if err != nil {
    35  		return util.NewErr(util.EcListenErr, util.M{
    36  			"addr":  l.addr,
    37  			"error": err.Error(),
    38  		})
    39  	}
    40  
    41  	l.listener, err = net.ListenTCP("tcp", addr)
    42  	if err != nil {
    43  		return util.NewErr(util.EcListenErr, util.M{
    44  			"addr":  l.addr,
    45  			"error": err.Error(),
    46  		})
    47  	}
    48  
    49  	go func() {
    50  		for {
    51  			conn, err := l.listener.AcceptTCP()
    52  			if err != nil {
    53  				kiwi.Error(util.WrapErr(util.EcAcceptErr, err))
    54  				return
    55  			}
    56  			l.onConn(conn)
    57  		}
    58  	}()
    59  	return nil
    60  }
    61  
    62  func (l *tcpListener) Close() {
    63  	if l.listener == nil {
    64  		return
    65  	}
    66  	l.listener.Close()
    67  }