我正在尝试实现一个 keepAlive 机制。问题是我不知道如何在没有竞争的情况下替换保持活动的股票代码 (conn.keepAlive),因为keepAlive()方法总是从股票代码中读取。
//errors not handled for brevity
const interval = 10 * time.Second
type conn struct {
keepAlive time.Ticker
conn net.Conn
mux sync.Mutex
}
// replace replaces the underlying connection
func (cn conn) replace(newcn net.Conn) {
cn.mux.Lock()
cn.conn = newcn
// reset the ticker
cn.keepAlive.Stop
cn.keepAlive = time.NewTicker(interval)
cn.mux.Unlock()
}
func (cn conn) keepAlive() {
for {
<-cn.keepAlive.C
cn.mux.Lock()
cn.conn.Write([]byte("ping"))
var msg []byte
cn.conn.Read(msg)
if string(msg) != "pong" {
// do some mean stuff
}
cn.keepAlive = time.NewTicker(interval)
cn.mux.Unlock()
}
}
神不在的星期二
富国沪深
相关分类