iedc-go/example/app/websocket.go
2022-03-16 09:58:24 +08:00

73 lines
1.3 KiB
Go

package app
import (
. "code.hoteas.com/golang/hotime"
. "code.hoteas.com/golang/hotime/common"
"golang.org/x/net/websocket"
"time"
)
type WSClient struct {
ID string
*websocket.Conn
time.Time
DeadTime time.Time
IsDead bool
}
//websocket链接池
var WsUserMap = map[string][]*WSClient{}
var WSMasterID = ""
func WsSendMsg(ws *WSClient, data Map) bool {
if WsUserMap[ws.ID] == nil {
return false
}
for _, v := range WsUserMap[ws.ID] {
if v.IsDead || v == ws {
//WsUserMap[ws.ID]=WsUserMap[ws.ID][:k]
continue
}
str := data.ToJsonString()
v.Conn.Write([]byte(str))
}
return true
}
var WebsocketCtr = Ctr{
"conn": func(this *Context) {
id := this.SessionId
if WsUserMap[id] == nil {
WsUserMap[id] = []*WSClient{}
}
hdler := websocket.Handler(func(ws *websocket.Conn) {
client := &WSClient{ID: id, Conn: ws, Time: time.Now(), DeadTime: time.Now(), IsDead: false}
WsUserMap[id] = append(WsUserMap[id], client)
var message string
for true {
err := websocket.Message.Receive(ws, &message)
if err != nil {
client.DeadTime = time.Now()
client.IsDead = true
return
}
data := Map{}
data.JsonToMap(message)
WsSendMsg(client, data)
//switch data.GetString("type") {
//
//}
}
})
hdler.ServeHTTP(this.Resp, this.Req)
},
}