RobotViewModel.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.ComponentModel.Composition;
  3. using System.IO;
  4. using System.Text;
  5. using System.Windows.Threading;
  6. using ENet;
  7. using Helper;
  8. using Log;
  9. using Microsoft.Practices.Prism.ViewModel;
  10. using ProtoBuf;
  11. using Robot.Protos;
  12. namespace Modules.Robot
  13. {
  14. [Export(contractType: typeof (RobotViewModel)), PartCreationPolicy(creationPolicy: CreationPolicy.NonShared)]
  15. internal sealed class RobotViewModel: NotificationObject, IDisposable
  16. {
  17. private readonly ClientHost clientHost;
  18. private string loginIp;
  19. private ushort loginPort;
  20. private readonly DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal)
  21. { Interval = new TimeSpan(0, 0, 0, 0, 50) };
  22. public string LoginIp
  23. {
  24. get
  25. {
  26. return this.loginIp;
  27. }
  28. set
  29. {
  30. if (this.loginIp == value)
  31. {
  32. return;
  33. }
  34. this.loginIp = value;
  35. this.RaisePropertyChanged("LoginIp");
  36. }
  37. }
  38. public ushort LoginPort
  39. {
  40. get
  41. {
  42. return this.loginPort;
  43. }
  44. set
  45. {
  46. if (this.loginPort == value)
  47. {
  48. return;
  49. }
  50. this.loginPort = value;
  51. this.RaisePropertyChanged("LoginPort");
  52. }
  53. }
  54. public RobotViewModel()
  55. {
  56. Library.Initialize();
  57. this.clientHost = new ClientHost();
  58. this.timer.Tick += delegate { this.clientHost.RunOnce(); };
  59. this.timer.Start();
  60. }
  61. ~RobotViewModel()
  62. {
  63. this.Disposing(false);
  64. }
  65. public void Dispose()
  66. {
  67. this.Disposing(true);
  68. GC.SuppressFinalize(this);
  69. }
  70. private void Disposing(bool disposing)
  71. {
  72. this.clientHost.Dispose();
  73. }
  74. public async void Login()
  75. {
  76. try
  77. {
  78. var address = new Address { HostName = this.LoginIp, Port = this.LoginPort };
  79. using (Peer peer = await this.clientHost.ConnectAsync(address))
  80. {
  81. using (Packet packet = await peer.ReceiveAsync())
  82. {
  83. var bytes = packet.Bytes;
  84. var packetStream = new MemoryStream(bytes, 4, bytes.Length - 4);
  85. var smsg = Serializer.Deserialize<SMSG_Auth_Challenge>(packetStream);
  86. Logger.Debug(string.Format(
  87. "opcode: {0}\n{1}", BitConverter.ToUInt16(bytes, 0), XmlHelper.XmlSerialize(smsg)));
  88. await peer.DisconnectLaterAsync();
  89. }
  90. }
  91. }
  92. catch (Exception e)
  93. {
  94. Logger.Debug(e.Message);
  95. }
  96. }
  97. }
  98. }