chanrpc.go 2.2 KB

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