BossClient.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Threading.Tasks;
  4. using ENet;
  5. using Log;
  6. namespace BossClient
  7. {
  8. public class BossClient : IDisposable
  9. {
  10. private int sessionId;
  11. private readonly ClientHost clientHost = new ClientHost();
  12. private GateSession gateSession;
  13. public void Dispose()
  14. {
  15. this.clientHost.Dispose();
  16. }
  17. public void RunOnce()
  18. {
  19. this.clientHost.RunOnce();
  20. }
  21. public void Start(int timeout)
  22. {
  23. this.clientHost.Start(timeout);
  24. }
  25. public async void HandleMessages()
  26. {
  27. if (this.gateSession == null)
  28. {
  29. throw new BossException("gate session is null");
  30. }
  31. await this.gateSession.HandleMessages();
  32. }
  33. public async Task Login(
  34. string hostName, ushort port, string account, string password)
  35. {
  36. int loginSessionId = ++this.sessionId;
  37. try
  38. {
  39. // 登录realm
  40. var tcpClient = new TcpClient();
  41. await tcpClient.ConnectAsync(hostName, port);
  42. Tuple<string, ushort, SRP6Client> realmInfo = null; // ip, port, K
  43. using (var realmSession = new RealmSession(loginSessionId, new TcpChannel(tcpClient)))
  44. {
  45. realmInfo = await realmSession.Login(account, password);
  46. Logger.Trace("session: {0}, login success!", realmSession.ID);
  47. }
  48. // 登录gate
  49. Peer peer = await this.clientHost.ConnectAsync(realmInfo.Item1, realmInfo.Item2);
  50. this.gateSession = new GateSession(loginSessionId, new ENetChannel(peer));
  51. await gateSession.Login(realmInfo.Item3);
  52. }
  53. catch (Exception e)
  54. {
  55. Logger.Trace("session: {0}, exception: {1}", loginSessionId, e.ToString());
  56. }
  57. }
  58. public void SendCommand(string command)
  59. {
  60. var cmsgBossGm = new CMSG_Boss_Gm
  61. {
  62. Message = command
  63. };
  64. this.gateSession.SendMessage(MessageOpcode.CMSG_BOSS_GM, cmsgBossGm);
  65. }
  66. }
  67. }