Go
// 处理ws请求
func WsHandler(w http.ResponseWriter, r *http.Request, id string) {
var conn *websocket.Conn
var err error
pingTicker := time.NewTicker(time.Second * 10)
conn, err = wsupgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Failed to set websocket upgrade: %+v", err)
return
}
addClient(id, conn)
m, exist := getMessageChannel(id)
if !exist {
m = make(chan interface{})
addMessageChannel(id, m)
}
conn.SetCloseHandler(func(code int, text string) error {
deleteClient(id)
fmt.Println(code)
return nil
})
for {
select {
case content, ok := <-m:
err = conn.WriteJSON(content)
if err != nil {
log.Println(err)
if ok {
go func() {
m <- content
}()
}
conn.Close()
deleteClient(id)
return
}
case <-pingTicker.C:
conn.SetWriteDeadline(time.Now().Add(time.Second * 20))
if err := conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
log.Println("send ping err:", err)
conn.Close()
deleteClient(id)
return
}
}
}
}