为了账号安全,请及时绑定邮箱和手机立即绑定

Go gorilla websocket 写入截止日期

Go gorilla websocket 写入截止日期

Go
Smart猫小萌 2022-12-05 17:30:38
我无法理解这部分使用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 这里的官方码头
查看完整描述

1 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

来自 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 消息设置读取截止日期和处理程序。根据您设置的等待时间,这种持续的乒乓球使连接保持活动状态。


查看完整回答
反对 回复 2022-12-05
  • 1 回答
  • 0 关注
  • 237 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号