Packet.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 = Native.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. if (disposing)
  43. {
  44. Native.enet_packet_destroy(this.packet);
  45. }
  46. this.packet = IntPtr.Zero;
  47. }
  48. private ENetPacket Struct
  49. {
  50. get
  51. {
  52. return (ENetPacket) Marshal.PtrToStructure(this.packet, typeof (ENetPacket));
  53. }
  54. set
  55. {
  56. Marshal.StructureToPtr(value, this.packet, false);
  57. }
  58. }
  59. public IntPtr NativePtr
  60. {
  61. get
  62. {
  63. return this.packet;
  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. }