Go gorilla websocket 写入截止日期

Go gorilla websocket write deadline

我无法理解使用 c.conn.SetWriteDeadline 函数的这部分代码。


    // Time allowed to write a message to the peer.
    writeWait = 10 * time.Second

    // Time allowed to read the next pong message from the peer.
    pongWait = 60 * time.Second

    // Send pings to peer with this period. Must be less than pongWait.
    pingPeriod = (pongWait * 9) / 10

// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
    ticker := time.NewTicker(pingPeriod)
    defer func() {
        ticker.Stop()
        c.conn.Close()
    }()
    for {
        select {
        case message, ok := <-c.send:
            // LOGIC TO WRITE MESSAGE TO THE CONNECTION
        case <-ticker.C: 
            c.conn.SetWriteDeadline(time.Now().Add(writeWait)) //  ??
            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
                return
            }
        }
    }
}

我无法理解票务渠道逻辑。我们要在这里实现什么目标?

我指的是 go/gorilla/websocket here

的官方码头

来自 SetWriteDeadline 函数文档:

SetWriteDeadline sets the write deadline on the underlying network connection. 
After a write has timed out, the websocket state is corrupt and
all future writes will return an error. 
A zero value for t means writes will not time out.

所以 goroutine 上的每个自动收报机都将写入截止日期设置为当前时间加上您将 writeWait const 设置为什么。随后的行然后发送一个带有该截止日期的 ping 消息。这一切都发生在代码间隔,即 const pingPeriod。另一个 go-routine,readPump(),应该为 pong 消息设置读取截止日期和处理程序。此常量 ping-pong 根据您设置的等待时间使连接保持活动状态。