我正在尝试实现keepAlive机制。问题在于,我不知道如何在不进行比赛的情况下替换保持 Activity 代码(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()
    }
}

最佳答案

一种更简洁地实现此方法的方法是,使用通道作为同步机制,而不是互斥体:

type conn struct {
    sync.Mutex
    conn        net.Conn
    replaceConn chan net.Conn
}

// replace replaces the underlying connection
func (cn *conn) replace(newcn net.Conn) {
    cn.replaceConn <- newcn
}

func (cn *conn) keepAlive() {
    t := time.NewTicker(interval)
    msg := make([]byte, 10)

    for {
        select {
        case <-t.C:
        case newConn := <-cn.replaceConn:
            cn.Lock()
            cn.conn = newConn
            cn.Unlock()
            continue
        }

        cn.Lock()
        _ = msg
        // do keepalive
        cn.Unlock()
    }
}

关于go - 如何在没有比赛的情况下延长股票行情的持续时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31973345/

10-11 07:16