chanrpc.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package internal
  2. import (
  3. "server/common"
  4. "server/msg"
  5. "server/user"
  6. "time"
  7. "github.com/name5566/leaf/gate"
  8. "github.com/name5566/leaf/log"
  9. )
  10. func init() {
  11. skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
  12. skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
  13. skeleton.RegisterChanRPC("handleAuth", handleAuth)
  14. }
  15. func rpcNewAgent(args []interface{}) {
  16. agent := args[0].(gate.Agent)
  17. // 将新连接放入未认证池
  18. pendingConns[agent] = &PendingConn{
  19. Agent: agent,
  20. CreateTime: time.Now().Unix(),
  21. Status: ConnStatusUnauth,
  22. }
  23. go checkTimeout(agent)
  24. }
  25. func rpcCloseAgent(args []interface{}) {
  26. log.Debug("rpcCloseAgent")
  27. agent := args[0].(gate.Agent)
  28. // 清理未认证连接
  29. _, exists := pendingConns[agent]
  30. if exists {
  31. delete(pendingConns, agent)
  32. }
  33. // 清理已认证连接
  34. for userID, a := range authedUsers {
  35. if a == agent {
  36. a.SetUserData(&common.UserData{
  37. Id: userID,
  38. Nickname: userID,
  39. Status: 0,
  40. })
  41. delete(authedUsers, userID)
  42. break
  43. }
  44. }
  45. }
  46. // 处理认证消息
  47. func handleAuth(args []interface{}) {
  48. // 收到的登录消息
  49. m := args[0].(*msg.ResLogin)
  50. // 消息的发送者
  51. a := args[1].(gate.Agent)
  52. log.Debug("handleAuth: nikeName=%v, userId=%v", m.NikeName, m.UserId)
  53. // 找到未认证连接
  54. if pending, exists := pendingConns[a]; exists {
  55. // 认证成功,移动到已认证池
  56. delete(pendingConns, a)
  57. authedUsers[m.UserId] = a
  58. pending.Status = ConnStatusAuthed
  59. // 处理可能的重复登录
  60. if oldAgent, exists := authedUsers[m.UserId]; exists && oldAgent != a {
  61. oldAgent.Close()
  62. delete(authedUsers, m.UserId)
  63. }
  64. // 获取用户信息 ,如果新用户则创建一个
  65. userData := user.GetUserInfoById(m.UserId)
  66. a.SetUserData(&common.UserData{
  67. Id: m.UserId,
  68. Nickname: m.UserId,
  69. Status: 1,
  70. })
  71. // 发送登录成功响应
  72. a.WriteMsg(&msg.ReqLogin{
  73. NikeName: m.UserId,
  74. UserId: m.UserId,
  75. Points: int32(userData.Points),
  76. GameStatus: "online",
  77. })
  78. }
  79. }
  80. // 定时检查超时连接
  81. func checkTimeout(agent gate.Agent) {
  82. timeout := 30 * time.Second
  83. timer := time.NewTimer(timeout)
  84. defer timer.Stop()
  85. select {
  86. case <-timer.C:
  87. // 检查是否仍在未认证池中
  88. if conn, exists := pendingConns[agent]; exists {
  89. if conn.Status == ConnStatusUnauth {
  90. // 超时未认证,关闭连接
  91. log.Debug("Connection timeout without auth, closing...")
  92. agent.Close()
  93. delete(pendingConns, agent)
  94. }
  95. }
  96. }
  97. }