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.
119 lines
2.3 KiB
Go
119 lines
2.3 KiB
Go
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"
|
|
"git.noahlan.cn/northlan/ntools-go/logger"
|
|
"github.com/golang/protobuf/proto"
|
|
"time"
|
|
)
|
|
|
|
const roomIDKey = "ROOM_ID"
|
|
|
|
type (
|
|
Room struct {
|
|
id int64
|
|
group *ngs.Group
|
|
}
|
|
|
|
Manager struct {
|
|
component.Base
|
|
timer *scheduler.Timer
|
|
rooms map[int64]*Room
|
|
}
|
|
)
|
|
|
|
func NewRoomManager() *Manager {
|
|
return &Manager{
|
|
rooms: make(map[int64]*Room),
|
|
}
|
|
}
|
|
|
|
func (m *Manager) CMD() string {
|
|
return "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())
|
|
}
|
|
})
|
|
}
|
|
|
|
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
|
|
|
|
var resp = &pb.JoinRoomResp{
|
|
Code: 200,
|
|
Result: "success",
|
|
}
|
|
|
|
err = room.group.Add(s)
|
|
if err != nil {
|
|
resp.Code = 500
|
|
resp.Result = "加入房间失败"
|
|
} else {
|
|
_ = room.group.Broadcast("onNewClient", &pb.Client{Id: msg.LiveRoomId})
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (m *Manager) PushToRoom(roomId int64, route string, msg proto.Message) {
|
|
if room, ok := m.rooms[roomId]; ok {
|
|
err := room.group.Broadcast(route, msg)
|
|
if err != nil {
|
|
logger.SLog.Errorf("broadcast message to room %d err:%+v", room.id, err)
|
|
}
|
|
}
|
|
}
|