You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
1.5 KiB
Go

3 years ago
package room
import (
"dcg/game/pb"
"fmt"
"git.noahlan.cn/northlan/ngs"
"git.noahlan.cn/northlan/ngs/component"
"git.noahlan.cn/northlan/ngs/scheduler"
"git.noahlan.cn/northlan/ngs/session"
"log"
"time"
)
const roomIDKey = "ROOM_ID"
type (
Room struct {
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 {
log.Println("join ?")
room, found := m.rooms[msg.LiveRoomId]
if !found {
room = &Room{
group: ngs.NewGroup(fmt.Sprintf("room-%s", 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",
})
}