Packet.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using Log;
  5. namespace ENet
  6. {
  7. public sealed class Packet: IDisposable
  8. {
  9. private IntPtr packet;
  10. public Packet(IntPtr packet)
  11. {
  12. this.packet = packet;
  13. }
  14. public Packet(byte[] data, PacketFlags flags = PacketFlags.None)
  15. {
  16. if (data == null)
  17. {
  18. throw new ArgumentNullException("data");
  19. }
  20. this.packet = NativeMethods.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. NativeMethods.enet_packet_destroy(this.packet);
  42. this.packet = IntPtr.Zero;
  43. }
  44. private ENetPacket Struct
  45. {
  46. get
  47. {
  48. return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
  49. }
  50. set
  51. {
  52. Marshal.StructureToPtr(value, this.packet, false);
  53. }
  54. }
  55. public IntPtr PacketPtr
  56. {
  57. get
  58. {
  59. return this.packet;
  60. }
  61. set
  62. {
  63. this.packet = value;
  64. }
  65. }
  66. public uint Length
  67. {
  68. get
  69. {
  70. if (this.packet == IntPtr.Zero)
  71. {
  72. return 0;
  73. }
  74. return this.Struct.dataLength;
  75. }
  76. }
  77. public byte[] Bytes
  78. {
  79. get
  80. {
  81. var enetPacket = this.Struct;
  82. var bytes = new byte[enetPacket.dataLength];
  83. Marshal.Copy(enetPacket.data, bytes, 0, (int) enetPacket.dataLength);
  84. return bytes;
  85. }
  86. }
  87. }
  88. }