1 Star 0 Fork 0

玟兵 / go-util

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
hub.go 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
玟兵 提交于 2023-11-23 21:38 . 增加Websocket
package ws
import "gitee.com/binny_w/go-util"
func NewHub(fn, fu func(*Client), fb func(*Message) error) *Hub {
hub := &Hub{
Clients: make(map[string]*Client),
Broadcast: make(chan *Message),
Register: make(chan *Client),
Unregister: make(chan *Client),
}
go hub.run(fn, fu, fb)
return hub
}
func (h *Hub) run(fn, fu func(*Client), fb func(*Message) error) {
for {
select {
case client := <-h.Register:
cid := client.Id
if clientOld, ok := h.Clients[cid]; ok {
cidOld := cid + "_old"
clientOld.Id = cidOld
h.Clients[cidOld] = clientOld
_ = clientOld.Conn.Close()
}
h.Clients[cid] = client
if fn != nil {
go fn(client) // Register Callback
}
case client := <-h.Unregister:
if _, ok := h.Clients[client.Id]; ok {
delete(h.Clients, client.Id)
}
close(client.Send)
if fu != nil {
go fu(client) // Unregister Callback
}
case msg := <-h.Broadcast:
if fb != nil && fb(msg) != nil { // Broadcast Callback
continue
}
if len(msg.Recipients) > 0 && len(msg.Groups) == 0 { // 如果明确了接收者,减少循环次数
for _, clientId := range msg.Recipients {
if client, ok := h.Clients[clientId]; ok {
select {
case client.Send <- msg:
default:
h.Unregister <- client
}
}
}
continue
}
for _, client := range h.Clients {
if client.Id == msg.Sender { // 不用发送给自己
continue
}
bln := len(msg.Recipients) == 0 && len(msg.Groups) == 0 // 未明确接收者和接收组,发给全员
if !bln && len(msg.Recipients) > 0 {
bln, _ = util.InArray(client.Id, msg.Recipients)
}
if !bln && len(client.Groups) > 0 && len(msg.Groups) > 0 {
for _, group := range client.Groups {
if bln, _ = util.InArray(group, msg.Groups); bln {
break
}
}
}
if !bln {
continue
}
select {
case client.Send <- msg:
default:
h.Unregister <- client
}
}
}
}
}
Go
1
https://gitee.com/binny_w/go-util.git
git@gitee.com:binny_w/go-util.git
binny_w
go-util
go-util
v0.0.19

搜索帮助