go websocket心跳

say_go發表於2017-09-01

在 github.com/gorilla/websocket 包裡,有一個簡單的例子,裡面有這麼一段程式碼

func (c *Client) writeData() {
    ticker := time.NewTicker(pingPeriod)
    defer func() {
        ticker.Stop()
        c.conn.Close()
    }()
    for {
        select {
        case message, ok := <-c.send:
            c.conn.SetWriteDeadline(time.Now().Add(writeTimeOut))
            if !ok {
                c.conn.WriteMessage(websocket.CloseMessage, []byte{})
                return
            }
            w, err := c.conn.NextWriter(websocket.TextMessage)
            if err != nil {
                return
            }
            log.Printf("writeData.....%s, uid is:%d", message, c.uid)
            w.Write(message)
            if err := w.Close(); err != nil {
                return
            }
            log.Printf("writeData.end....%s", message)
        case <-ticker.C:
            log.Println("here.....")
            c.conn.SetWriteDeadline(time.Now().Add(writeTimeOut))
            if err := c.conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
                return
            }
        }
    }
}

c.conn.WriteMessage(websocket.PingMessage, [] byte{}) 是向 client 傳送 ping 資訊,怎麼沒看到處理 client pong 訊息的程式碼呢? gorilla/websocket 是怎麼處理 pong 訊息的呢?看了半天也沒找到。

更多原創文章乾貨分享,請關注公眾號
  • go websocket心跳
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章