Packet.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace ENet
  4. {
  5. public sealed class Packet: IDisposable
  6. {
  7. private Host host;
  8. private IntPtr packet;
  9. public Packet(Host host, IntPtr packet)
  10. {
  11. this.host = host;
  12. this.packet = packet;
  13. }
  14. public Packet(string data, PacketFlags flags = PacketFlags.None)
  15. {
  16. if (data == null)
  17. {
  18. throw new ArgumentNullException("data");
  19. }
  20. this.packet = Native.enet_packet_create(data, (uint) data.Length, flags);
  21. if (this.packet == IntPtr.Zero)
  22. {
  23. throw new ENetException(0, "Packet creation call failed.");
  24. }
  25. }
  26. ~Packet()
  27. {
  28. this.Dispose(false);
  29. }
  30. public void Dispose()
  31. {
  32. this.Dispose(true);
  33. GC.SuppressFinalize(this);
  34. }
  35. private void Dispose(bool disposing)
  36. {
  37. if (this.packet == IntPtr.Zero)
  38. {
  39. return;
  40. }
  41. if (disposing)
  42. {
  43. Native.enet_packet_destroy(this.packet);
  44. }
  45. this.packet = IntPtr.Zero;
  46. }
  47. private ENetPacket Struct
  48. {
  49. get
  50. {
  51. return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
  52. }
  53. set
  54. {
  55. Marshal.StructureToPtr(value, this.packet, false);
  56. }
  57. }
  58. public IntPtr NativePtr
  59. {
  60. get
  61. {
  62. return this.packet;
  63. }
  64. }
  65. public uint Length
  66. {
  67. get
  68. {
  69. if (this.packet == IntPtr.Zero)
  70. {
  71. return 0;
  72. }
  73. return this.Struct.dataLength;
  74. }
  75. }
  76. public string Data
  77. {
  78. get
  79. {
  80. if (this.packet == IntPtr.Zero)
  81. {
  82. return "";
  83. }
  84. ENetPacket pkt = this.Struct;
  85. if (pkt.data == IntPtr.Zero)
  86. {
  87. return "";
  88. }
  89. return Marshal.PtrToStringAuto(pkt.data, (int) pkt.dataLength);
  90. }
  91. }
  92. }
  93. }