Go gorilla websocket 写入截止日期

我无法理解这部分使用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 这里的官方码头


Smart猫小萌
浏览 238回答 1
1回答

慕雪6442864

来自 SetWriteDeadline 函数文档:SetWriteDeadline sets the write deadline on the underlying network connection.&nbsp;After a write has timed out, the websocket state is corrupt andall future writes will return an error.&nbsp;A zero value for t means writes will not time out.因此,goroutine 上的每个自动收报机都将写入截止日期设置为当前时间加上您将 writeWait const 设置为的任何内容。随后的行然后发送一个带有该截止日期的 ping 消息。这一切都发生在代码间隔,即 const pingPeriod。另一个 go-routine,readPump(),应该为 pong 消息设置读取截止日期和处理程序。根据您设置的等待时间,这种持续的乒乓球使连接保持活动状态。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go