// 处理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
}()
golang websocket 手写研究机制
最新推荐文章于 2024-11-09 09:27:35 发布