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.

106 lines
2.0 KiB
Go

3 years ago
package room
import (
"dcg/game/pb"
"dcg/pkg/logger"
3 years ago
"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"
3 years ago
"time"
)
const roomIDKey = "ROOM_ID"
type (
Room struct {
id int64
3 years ago
group *ngs.Group
}
Manager struct {
component.Base
timer *scheduler.Timer
3 years ago
rooms map[int64]*Room
}
)
func NewRoomManager() *Manager {
return &Manager{
rooms: make(map[int64]*Room),
}
}
func (m *Manager) Init() {
}
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)
})
m.timer = scheduler.NewTimer(30*time.Second, func() {
for roomId, room := range m.rooms {
logger.SLog.Debugf("UserCount: RoomID=%d, Time=%s, Count=%d",
roomId, time.Now().String(), room.group.Count())
}
})
3 years ago
}
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)),
3 years ago
}
m.rooms[msg.LiveRoomId] = room
}
// uid - liveRoomId
err := s.Bind(msg.LiveRoomId)
if err != nil {
return err
}
s.Set(roomIDKey, room)
// members
var resp = &pb.JoinRoomResp{
Code: 200,
Result: "success",
}
3 years ago
err = room.group.Add(s)
if err != nil {
resp.Code = 500
resp.Result = "加入房间失败"
} else {
_ = room.group.Broadcast("onNewClient", &pb.Client{Id: msg.LiveRoomId})
}
3 years ago
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)
}
}
}