RealmSession.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using Helper;
  6. using Log;
  7. using Org.BouncyCastle.Utilities.Encoders;
  8. using ProtoBuf;
  9. using Robot.Protos;
  10. using Helper;
  11. using Org.BouncyCastle.Crypto.Digests;
  12. namespace Robot
  13. {
  14. public class RealmSession: IDisposable
  15. {
  16. private readonly NetworkStream networkStream;
  17. public RealmSession(string host, ushort port)
  18. {
  19. Socket socket = ConnectSocket(host, port);
  20. networkStream = new NetworkStream(socket);
  21. }
  22. public void Dispose()
  23. {
  24. networkStream.Dispose();
  25. }
  26. public static Socket ConnectSocket(string host, ushort port)
  27. {
  28. IPHostEntry hostEntry = Dns.GetHostEntry(host);
  29. foreach (IPAddress address in hostEntry.AddressList)
  30. {
  31. var ipe = new IPEndPoint(address, port);
  32. var tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  33. tempSocket.Connect(ipe);
  34. if (!tempSocket.Connected)
  35. {
  36. continue;
  37. }
  38. return tempSocket;
  39. }
  40. Logger.Debug("socket is null, address: {0}:{1}", host, port);
  41. throw new SocketException(10000);
  42. }
  43. public async void SendMessage<T>(ushort opcode, T message)
  44. {
  45. byte[] protoBytes = ProtobufHelper.ProtoToBytes(message);
  46. var neworkBytes = new byte[sizeof(int) + sizeof(ushort) + protoBytes.Length];
  47. int totalSize = sizeof(ushort) + protoBytes.Length;
  48. var totalSizeBytes = BitConverter.GetBytes(totalSize);
  49. totalSizeBytes.CopyTo(neworkBytes, 0);
  50. var opcodeBytes = BitConverter.GetBytes(opcode);
  51. opcodeBytes.CopyTo(neworkBytes, sizeof(int));
  52. protoBytes.CopyTo(neworkBytes, sizeof(int) + sizeof(ushort));
  53. await networkStream.WriteAsync(neworkBytes, 0, neworkBytes.Length);
  54. }
  55. public void Login(string account, string password)
  56. {
  57. try
  58. {
  59. byte[] passwordBytes = password.ToByteArray();
  60. var digest = new MD5Digest();
  61. var passwordMd5 = new byte[digest.GetDigestSize()];
  62. digest.BlockUpdate(passwordBytes, 0, passwordBytes.Length);
  63. digest.DoFinal(passwordMd5, 0);
  64. var cmsgAuthLogonPermit = new CMSG_AuthLogonPermit
  65. {
  66. Account = account,
  67. PasswordMd5 = Hex.ToHexString(passwordMd5)
  68. };
  69. Logger.Debug("password: {0}", cmsgAuthLogonPermit.PasswordMd5);
  70. SendMessage(MessageOpcode.CMSG_AUTHLOGONPERMIT, cmsgAuthLogonPermit);
  71. }
  72. catch (SocketException e)
  73. {
  74. Logger.Debug("socket exception, error: {}", e.ErrorCode);
  75. }
  76. }
  77. }
  78. }