BossClient.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. try
  32. {
  33. await this.gateSession.HandleMessages();
  34. }
  35. catch (BossException e)
  36. {
  37. Logger.Trace("session: {0}, exception: {1}", this.gateSession.ID, e.ToString());
  38. }
  39. }
  40. public async Task Login(
  41. string hostName, ushort port, string account, string password)
  42. {
  43. int loginSessionId = ++this.sessionId;
  44. try
  45. {
  46. // 登录realm
  47. var tcpClient = new TcpClient();
  48. await tcpClient.ConnectAsync(hostName, port);
  49. Tuple<string, ushort, SRP6Client> realmInfo = null; // ip, port, K
  50. using (var realmSession = new RealmSession(loginSessionId, new TcpChannel(tcpClient)))
  51. {
  52. realmInfo = await realmSession.Login(account, password);
  53. Logger.Trace("session: {0}, login success!", realmSession.ID);
  54. }
  55. // 登录gate
  56. Peer peer = await this.clientHost.ConnectAsync(realmInfo.Item1, realmInfo.Item2);
  57. this.gateSession = new GateSession(loginSessionId, new ENetChannel(peer));
  58. await gateSession.Login(realmInfo.Item3);
  59. }
  60. catch (Exception e)
  61. {
  62. Logger.Trace("session: {0}, exception: {1}", loginSessionId, e.ToString());
  63. }
  64. }
  65. public void SendCommand(string command)
  66. {
  67. var cmsgBossGm = new CMSG_Boss_Gm
  68. {
  69. Message = command
  70. };
  71. this.gateSession.SendMessage(MessageOpcode.CMSG_BOSS_GM, cmsgBossGm);
  72. }
  73. }
  74. }