I have a function as follows:
func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {
addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)
for {
<-err
time.Sleep(reconnectTimer)
conn, _ := net.Dial(n.Network, addr)
w <- conn
}
}
The goal is to redial a connection when I receive an error from a err chan
. But I don't want to redial if I'm already dialing or within a certain time duration. However I may receive alot of errors I don't want to block.
How could I do that?
EDIT
Solution I've implemented so far :
func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {
addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)
done := make(chan bool)
isDialing := false
for {
select {
case <-err:
if !isDialing {
isDialing = true
time.AfterFunc(reconnectTimer, func() {
done <- true
})
}
case <-done:
conn, _ := net.Dial(n.Network, addr)
w <- conn
isDialing = false
}
}
}
CodePudding user response:
maybe you could use sync.WaitGroup
to make sure that there is only one call to redial after errors.
CodePudding user response:
type Conn struct {
conn net.Conn
dialing bool
mu sync.Mutex
}
func (c Conn) Dial() {
c.mu.Lock()
if c.dialing {
c.mu.Unlock()
return
}
c.dialing = true
c.mu.Unlock()
time.AfterFunc(reconnectTimer, func() {
c.conn, _ := net.Dial(n.Network, addr)
w <- c.conn
c.dialing = false
})
}
now you can call Conn.Dial()
in a go routine