csconnectplayerlogic.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package logic
  2. import (
  3. "context"
  4. "github.com/bytedance/sonic"
  5. "github.com/gookit/event"
  6. treemap "github.com/liyue201/gostl/ds/map"
  7. "github.com/robfig/cron/v3"
  8. "github.com/zeromicro/go-zero/core/logx"
  9. "time"
  10. "ylink/comm/model"
  11. "ylink/core/inner/rpc/internal/ext"
  12. "ylink/core/inner/rpc/internal/svc"
  13. "ylink/core/inner/rpc/pb"
  14. )
  15. type CsConnectPlayerLogic struct {
  16. ctx context.Context
  17. svcCtx *svc.ServiceContext
  18. logx.Logger
  19. }
  20. func NewCsConnectPlayerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CsConnectPlayerLogic {
  21. return &CsConnectPlayerLogic{
  22. ctx: ctx,
  23. svcCtx: svcCtx,
  24. Logger: logx.WithContext(ctx),
  25. }
  26. }
  27. func (l *CsConnectPlayerLogic) CsConnectPlayer(in *pb.InnerCsConnectPlayerReq) (*pb.InnerCsConnectPlayerResp, error) {
  28. playerInfo := ext.GetOnlinePlayerInfo(in.GameId, in.PlayerId)
  29. playerInfo.CsId = in.CsId
  30. playerInfo.DequeueTs = time.Now().Unix()
  31. if ext.GameConnectedMap.Contains(in.GameId) {
  32. playerConnectedMap := ext.GameConnectedMap.Get(in.GameId).(*treemap.Map)
  33. playerConnectedMap.Insert(in.PlayerId, playerInfo)
  34. } else {
  35. playerConnectedMap := treemap.New(treemap.WithGoroutineSafe())
  36. playerConnectedMap.Insert(in.PlayerId, playerInfo)
  37. ext.GameConnectedMap.Insert(in.GameId, playerConnectedMap)
  38. }
  39. // 移除WaitingQueue
  40. for n := ext.WaitingList.FrontNode(); n != nil; n = n.Next() {
  41. playerInfo := n.Value.(*model.PlayerInfo)
  42. if playerInfo.GameId == in.GameId && playerInfo.PlayerId == in.PlayerId {
  43. l.Logger.Infof("remove the player from the queue, game_id: %s, player_id: %s", in.GameId, in.PlayerId)
  44. ext.WaitingList.Remove(nil, n)
  45. break
  46. }
  47. }
  48. var entryId cron.EntryID
  49. entryId, _ = l.svcCtx.TimeoutCron.AddFunc("@every 1m", func() {
  50. // TODO 增加trace
  51. var timeoutTs int64
  52. if playerInfo.LastChatTs == 0 {
  53. timeoutTs = time.Now().Unix() - playerInfo.ConnectTs
  54. } else {
  55. timeoutTs = time.Now().Unix() - playerInfo.LastChatTs
  56. }
  57. if timeoutTs >= 300 {
  58. _ = event.MustFire(ext.EVENT_REMOVE_TIMEOUT_JOB, event.M{"entry_id": entryId})
  59. l.Logger.Infof("trigger timeout event, remove cron job, entry id: %d", entryId)
  60. // 发下线command
  61. //ext, _ := sonic.Marshal(playerInfo)
  62. message, _ := sonic.MarshalString(&model.KqCmdMessage{
  63. Opt: model.CMD_CHAT_TIMEOUT,
  64. Ext: playerInfo,
  65. })
  66. l.svcCtx.KqCmdBoxProducer.SendMessage(l.ctx, message, in.PlayerId)
  67. }
  68. })
  69. return &pb.InnerCsConnectPlayerResp{}, nil
  70. }