使用扩展:github.com/gorilla/websocket
对client的消息写与心跳如下:
```golang
func (c *Client) write() {
pingTicker := time.NewTicker(pingPeriod)
defer func() {
pingTicker.Stop()
Manager.Unregister <- c
c.Socket.Close()
}()
for {
select {
case point, ok := <-c.send:
if !ok {
c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
fmt.Println("send err:", point)
return
}
point.PushTime = time.Now().Unix()
msg, _ := json.Marshal(point)
fmt.Println(point.Content)
writeMessage := c.Socket.WriteMessage(websocket.TextMessage, msg)
if writeMessage != nil {
offline(point)
}
case <-pingTicker.C:
c.Socket.SetWriteDeadline(time.Now().Add(writeWait))
err := c.Socket.WriteMessage(websocket.PingMessage, []byte("ping"))
c.Socket.WriteMessage(websocket.TextMessage, []byte("ping"))
if err != nil {
fmt.Println("time out:", err)
return
}
}
}
}
```
正常情况下使用conn.send <- point投递消息,client都正确接收了(50ms/条 10000条)
但是客户端手动断网之后(异常离线),当pingTicker.C响应到client离线时,出现了消息丢失的情况即client最后一条消息与离线消息断层.
也就是client异常离线后c.Socket.WriteMessage(websocket.TextMessage, msg)正常发送了消息 err==nil无法触发offline方法.
求问:如何修改才能保障消息的不丢失?
有疑问加站长微信联系(非本文作者)