RobotViewModel.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. this.clientHost = new ClientHost();
  57. this.timer.Tick += delegate { this.clientHost.RunOnce(); };
  58. this.timer.Start();
  59. }
  60. ~RobotViewModel()
  61. {
  62. this.Disposing(false);
  63. }
  64. public void Dispose()
  65. {
  66. this.Disposing(true);
  67. GC.SuppressFinalize(this);
  68. }
  69. private void Disposing(bool disposing)
  70. {
  71. this.clientHost.Dispose();
  72. }
  73. public async void Login()
  74. {
  75. try
  76. {
  77. var address = new Address { HostName = this.LoginIp, Port = this.LoginPort };
  78. using (Peer peer = await this.clientHost.ConnectAsync(address))
  79. {
  80. using (Packet packet = await peer.ReceiveAsync())
  81. {
  82. var bytes = packet.Bytes;
  83. var packetStream = new MemoryStream(bytes, 4, bytes.Length - 4);
  84. var smsg = Serializer.Deserialize<SMSG_Auth_Challenge>(packetStream);
  85. Logger.Debug(string.Format("opcode: {0}\n{1}",
  86. BitConverter.ToUInt16(bytes, 0), XmlHelper.XmlSerialize(smsg)));
  87. await peer.DisconnectLaterAsync();
  88. }
  89. }
  90. }
  91. catch (Exception e)
  92. {
  93. Logger.Debug(e.Message);
  94. }
  95. }
  96. }
  97. }