Files
be.ems/src/modules/ws/service/ws_send.impl.go
2024-01-23 18:06:44 +08:00

73 lines
1.4 KiB
Go

package service
import (
"encoding/json"
"fmt"
"ems.agt/src/modules/ws/model"
)
const (
// 组号-其他
GROUP_OTHER = "0"
// 组号-指标
GROUP_KPI = "1000"
// 组号-会话记录
GROUP_CDR = "1005"
)
// 实例化服务层 WSSendImpl 结构体
var NewWSSendImpl = &WSSendImpl{}
// IWSSend WebSocket消息发送处理 服务层处理
type WSSendImpl struct{}
// ByClientID 给已知客户端发消息
func (s *WSSendImpl) ByClientID(clientID string, data any) error {
v, ok := WsClients.Load(clientID)
if !ok {
return fmt.Errorf("no fount client ID: %s", clientID)
}
dataByte, err := json.Marshal(data)
if err != nil {
return err
}
client := v.(*model.WSClient)
client.MsgChan <- dataByte
return nil
}
// ByGroupID 给订阅组的用户发送消息
func (s *WSSendImpl) ByGroupID(groupID string, data any) error {
uids, ok := WsGroup.Load(groupID)
if !ok {
return fmt.Errorf("no fount Group ID: %s", groupID)
}
groupUids := uids.(*[]string)
// 群组中没有成员
if len(*groupUids) == 0 {
return fmt.Errorf("no members in the group")
}
// 在群组中找到对应的 uid
for _, uid := range *groupUids {
clientIds, ok := WsUsers.Load(uid)
if !ok {
continue
}
// 在用户中找到客户端并发送
uidClientIds := clientIds.(*[]string)
for _, clientId := range *uidClientIds {
err := s.ByClientID(clientId, data)
if err != nil {
continue
}
}
}
return nil
}