Skip to content

Commit

Permalink
conn_listener: Refactor with sync
Browse files Browse the repository at this point in the history
  • Loading branch information
liberal-boy committed Jan 4, 2025
1 parent 251a2d9 commit dc9478b
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions handler/conn_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package handler
import (
"errors"
"net"
"sync"
)

var ErrNetClosing = errors.New("use of closed network connection")
Expand All @@ -11,6 +12,8 @@ type ConnListener struct {
isClosed bool
connChan chan net.Conn
exitChan chan struct{}
mu sync.Mutex
once sync.Once
}

func NewConnListener() *ConnListener {
Expand All @@ -33,21 +36,26 @@ func (c *ConnListener) Accept() (net.Conn, error) {
}

func (c *ConnListener) Close() error {
if c.isClosed {
return ErrNetClosing
}
c.isClosed = true
c.exitChan <- struct{}{}
close(c.exitChan)
close(c.connChan)
c.once.Do(func() {
c.mu.Lock()
defer c.mu.Unlock()
if c.isClosed {
return
}
c.isClosed = true
close(c.exitChan)
close(c.connChan)
})
return nil
}

func (c *ConnListener) Addr() net.Addr {
return nil
return &net.TCPAddr{IP: net.IPv4zero, Port: 0}
}

func (c *ConnListener) HandleConn(conn net.Conn) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.isClosed {
return ErrNetClosing
}
Expand Down

0 comments on commit dc9478b

Please sign in to comment.