Packet.cs 1.6 KB

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