package room import ( "dcg/game/pb" "dcg/pkg/logger" "fmt" "git.noahlan.cn/northlan/ngs" "git.noahlan.cn/northlan/ngs/component" "git.noahlan.cn/northlan/ngs/scheduler" "git.noahlan.cn/northlan/ngs/session" "github.com/golang/protobuf/proto" "time" ) const roomIDKey = "ROOM_ID" type ( Room struct { id int64 group *ngs.Group } Manager struct { component.Base rooms map[int64]*Room } ) func NewRoomManager() *Manager { return &Manager{ rooms: make(map[int64]*Room), } } func (m *Manager) Init() { scheduler.NewTimer(5*time.Second, func() { for _, room := range m.rooms { room.group.Broadcast("onInterval", &pb.Test{T: time.Now().UnixNano()}) } }) } func (m *Manager) AfterInit() { session.Lifetime.OnClosed(func(s *session.Session) { if !s.HasKey(roomIDKey) { return } room := s.Value(roomIDKey).(*Room) _ = room.group.Leave(s) }) } func (m *Manager) Shutdown() { for _, room := range m.rooms { _ = room.group.LeaveAll() } } func (m *Manager) Join(s *session.Session, msg *pb.JoinRoomReq) error { room, found := m.rooms[msg.LiveRoomId] if !found { room = &Room{ id: msg.LiveRoomId, group: ngs.NewGroup(fmt.Sprintf("room-%d", msg.LiveRoomId)), } m.rooms[msg.LiveRoomId] = room } // uid - liveRoomId err := s.Bind(msg.LiveRoomId) if err != nil { return err } s.Set(roomIDKey, room) // members room.group.Broadcast("onNewClient", &pb.Client{Id: msg.LiveRoomId}) room.group.Add(s) return s.Response(&pb.JoinRoomResp{ Code: 200, Result: "success", }) } func (m *Manager) Broadcast(route string, msg proto.Message) { for _, room := range m.rooms { err := room.group.Broadcast(route, msg) if err != nil { logger.SLog.Errorf("broadcast message to room %d err:%+v", room.id, err) } } }