func writer(ws *websocket.Conn) {
pingTicker := time.NewTicker(time.Second * 1)
fileTicker := time.NewTicker(time.Second * 1)
defer func() {
pingTicker.Stop()
fileTicker.Stop()
ws.Close()
}()
for {
select {
case
ws.SetWriteDeadline(time.Now().Add(time.Second * 2))
fmt.Println("------>hello")
if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
fmt.Println("send msg err:", err)
return
}
case
ws.SetWriteDeadline(time.Now().Add(time.Second * 2))
fmt.Println("---->send ping")
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
fmt.Println("send ping err:", err)
return
}
}
}
}
func reader(ws *websocket.Conn) {
ws.SetReadLimit(512)
ws.SetReadDeadline(time.Now().Add(time.Second * 2))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(time.Second * 2)); return nil })
defer ws.Close()
for {
t, msg, err := ws.ReadMessage()
fmt.Println("server recieve t:", t)
fmt.Println("server recieve body:", string(msg))
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
fmt.Println("error:", err)
}
return
}
time.Sleep(time.Second *5)
}
}
在 main 函数中,writer 函数必须加关键字 go,开启两个定时器,一个定时向客户端推送消息,一个定时 ping 客户端检测是否连接正常。如果断开显示send ping err: write tcp 127.0.0.1:3000->127.0.0.1:62228: write: broken pipe。但是感觉这个 ping 的定时器没啥用啊,如果客户端断开,WriteMessage 这个方法就会报错退出,那这个 ping 效果和它一样的,请问还有必要吗?
go writer(conn)
go reader(conn)