BossMonit.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 
  2. using System;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. using ProtoBuf;
  8. // 这个库要用到protobuf-net库,用Nuget安装即可
  9. namespace BossMonit
  10. {
  11. static class InternalApi
  12. {
  13. [DllImport("internal.dll")]
  14. public static extern ulong hash_string(string data, int size);
  15. };
  16. public static class ProtobufHelper
  17. {
  18. public static byte[] ToBytes<T>(T message)
  19. {
  20. var ms = new MemoryStream();
  21. Serializer.Serialize(ms, message);
  22. return ms.ToArray();
  23. }
  24. public static T FromBytes<T>(byte[] bytes)
  25. {
  26. var ms = new MemoryStream(bytes, 0, bytes.Length);
  27. return Serializer.Deserialize<T>(ms);
  28. }
  29. public static T FromBytes<T>(byte[] bytes, int index, int length)
  30. {
  31. var ms = new MemoryStream(bytes, index, length);
  32. return Serializer.Deserialize<T>(ms);
  33. }
  34. }
  35. public class BossMonit: IDisposable
  36. {
  37. private readonly TcpClient tcpClient;
  38. public BossMonit(string host, ushort port)
  39. {
  40. this.tcpClient = new TcpClient();
  41. this.tcpClient.Connect(host, port);
  42. }
  43. public GmResult GmControl(GmRequest request)
  44. {
  45. var stream = tcpClient.GetStream();
  46. // 发送
  47. // magic_num
  48. stream.WriteByte(0xAA);
  49. // call_guid, 同步调用这个字段随意设置
  50. var bytes = BitConverter.GetBytes((ulong) 0);
  51. stream.Write(bytes, 0, bytes.Length);
  52. // method_id
  53. const string method_full_name = "boss.GmControl";
  54. ulong method_id = InternalApi.hash_string(method_full_name, method_full_name.Length);
  55. bytes = BitConverter.GetBytes(method_id);
  56. var requestBytes = ProtobufHelper.ToBytes(request);
  57. // size
  58. bytes = BitConverter.GetBytes(requestBytes.Length);
  59. stream.Write(bytes, 0, bytes.Length);
  60. // request content
  61. stream.Write(requestBytes, 0, requestBytes.Length);
  62. // 接收
  63. var recvBuffer = new byte[21];
  64. stream.Read(recvBuffer, 0, recvBuffer.Length);
  65. Debug.Assert(recvBuffer[0] == 0xAA);
  66. uint return_size = BitConverter.ToUInt32(recvBuffer, 1 + 8 + 8);
  67. recvBuffer = new byte[return_size];
  68. stream.Read(recvBuffer, 0, recvBuffer.Length);
  69. var response = ProtobufHelper.FromBytes<GmResult>(recvBuffer);
  70. return response;
  71. }
  72. public void Dispose()
  73. {
  74. tcpClient.Close();
  75. }
  76. }
  77. }