ENet.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194
  1. /*
  2. * Managed C# wrapper for an extended version of ENet
  3. * Copyright (c) 2019 Matt Coburn (SoftwareGuy/Coburn64), Chris Burns (c6burns)
  4. * Copyright (c) 2013 - 2018 James Bellinger, Nate Shoffner, Stanislav Denisov
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. * SOFTWARE.
  23. */
  24. using System;
  25. using System.Runtime.InteropServices;
  26. using System.Security;
  27. using System.Text;
  28. namespace ENet
  29. {
  30. [Flags]
  31. public enum PacketFlags
  32. {
  33. None = 0,
  34. Reliable = 1 << 0,
  35. Unsequenced = 1 << 1,
  36. NoAllocate = 1 << 2,
  37. UnreliableFragmented = 1 << 3,
  38. Instant = 1 << 4
  39. }
  40. public enum EventType
  41. {
  42. None = 0,
  43. Connect = 1,
  44. Disconnect = 2,
  45. Receive = 3,
  46. Timeout = 4
  47. }
  48. public enum PeerState
  49. {
  50. Uninitialized = -1,
  51. Disconnected = 0,
  52. Connecting = 1,
  53. AcknowledgingConnect = 2,
  54. ConnectionPending = 3,
  55. ConnectionSucceeded = 4,
  56. Connected = 5,
  57. DisconnectLater = 6,
  58. Disconnecting = 7,
  59. AcknowledgingDisconnect = 8,
  60. Zombie = 9
  61. }
  62. [StructLayout(LayoutKind.Explicit, Size = 18)]
  63. internal struct ENetAddress
  64. {
  65. [FieldOffset(16)]
  66. public ushort port;
  67. }
  68. [StructLayout(LayoutKind.Sequential)]
  69. internal struct ENetEvent
  70. {
  71. public EventType type;
  72. public IntPtr peer;
  73. public byte channelID;
  74. public uint data;
  75. public IntPtr packet;
  76. }
  77. [StructLayout(LayoutKind.Sequential)]
  78. internal struct ENetCallbacks
  79. {
  80. public AllocCallback malloc;
  81. public FreeCallback free;
  82. public NoMemoryCallback noMemory;
  83. }
  84. public delegate IntPtr AllocCallback(IntPtr size);
  85. public delegate void FreeCallback(IntPtr memory);
  86. public delegate void NoMemoryCallback();
  87. public delegate void PacketFreeCallback(Packet packet);
  88. internal static class ArrayPool
  89. {
  90. [ThreadStatic]
  91. private static byte[] byteBuffer;
  92. [ThreadStatic]
  93. private static IntPtr[] pointerBuffer;
  94. public static byte[] GetByteBuffer()
  95. {
  96. if (byteBuffer == null)
  97. byteBuffer = new byte[64];
  98. return byteBuffer;
  99. }
  100. public static IntPtr[] GetPointerBuffer()
  101. {
  102. if (pointerBuffer == null)
  103. pointerBuffer = new IntPtr[Library.maxPeers];
  104. return pointerBuffer;
  105. }
  106. }
  107. public struct Address
  108. {
  109. private ENetAddress nativeAddress;
  110. internal ENetAddress NativeData {
  111. get {
  112. return nativeAddress;
  113. }
  114. set {
  115. nativeAddress = value;
  116. }
  117. }
  118. internal Address(ENetAddress address)
  119. {
  120. nativeAddress = address;
  121. }
  122. public ushort Port {
  123. get {
  124. return nativeAddress.port;
  125. }
  126. set {
  127. nativeAddress.port = value;
  128. }
  129. }
  130. public string GetIP()
  131. {
  132. StringBuilder ip = new StringBuilder(1024);
  133. if (Native.enet_address_get_host_ip(nativeAddress, ip, (IntPtr)ip.Capacity) != 0)
  134. return String.Empty;
  135. return ip.ToString();
  136. }
  137. public bool SetIP(string ip)
  138. {
  139. if (ip == null)
  140. throw new ArgumentNullException("ip");
  141. return Native.enet_address_set_host_ip(ref nativeAddress, ip) == 0;
  142. }
  143. public string GetHost()
  144. {
  145. StringBuilder hostName = new StringBuilder(1024);
  146. if (Native.enet_address_get_host(nativeAddress, hostName, (IntPtr)hostName.Capacity) != 0)
  147. return String.Empty;
  148. return hostName.ToString();
  149. }
  150. public bool SetHost(string hostName)
  151. {
  152. if (hostName == null)
  153. throw new ArgumentNullException("hostName");
  154. return Native.enet_address_set_host(ref nativeAddress, hostName) == 0;
  155. }
  156. }
  157. public struct Event
  158. {
  159. private ENetEvent nativeEvent;
  160. internal ENetEvent NativeData {
  161. get {
  162. return nativeEvent;
  163. }
  164. set {
  165. nativeEvent = value;
  166. }
  167. }
  168. internal Event(ENetEvent @event)
  169. {
  170. nativeEvent = @event;
  171. }
  172. public EventType Type {
  173. get {
  174. return nativeEvent.type;
  175. }
  176. }
  177. public Peer Peer {
  178. get {
  179. return new Peer(nativeEvent.peer);
  180. }
  181. }
  182. public byte ChannelID {
  183. get {
  184. return nativeEvent.channelID;
  185. }
  186. }
  187. public uint Data {
  188. get {
  189. return nativeEvent.data;
  190. }
  191. }
  192. public Packet Packet {
  193. get {
  194. return new Packet(nativeEvent.packet);
  195. }
  196. }
  197. }
  198. public class Callbacks
  199. {
  200. private ENetCallbacks nativeCallbacks;
  201. internal ENetCallbacks NativeData {
  202. get {
  203. return nativeCallbacks;
  204. }
  205. set {
  206. nativeCallbacks = value;
  207. }
  208. }
  209. public Callbacks(AllocCallback allocCallback, FreeCallback freeCallback, NoMemoryCallback noMemoryCallback)
  210. {
  211. nativeCallbacks.malloc = allocCallback;
  212. nativeCallbacks.free = freeCallback;
  213. nativeCallbacks.noMemory = noMemoryCallback;
  214. }
  215. }
  216. public struct Packet : IDisposable
  217. {
  218. private IntPtr nativePacket;
  219. internal IntPtr NativeData {
  220. get {
  221. return nativePacket;
  222. }
  223. set {
  224. nativePacket = value;
  225. }
  226. }
  227. internal Packet(IntPtr packet)
  228. {
  229. nativePacket = packet;
  230. }
  231. public void Dispose()
  232. {
  233. if (nativePacket != IntPtr.Zero)
  234. {
  235. Native.enet_packet_dispose(nativePacket);
  236. nativePacket = IntPtr.Zero;
  237. }
  238. }
  239. public bool IsSet {
  240. get {
  241. return nativePacket != IntPtr.Zero;
  242. }
  243. }
  244. public IntPtr Data {
  245. get {
  246. CheckCreated();
  247. return Native.enet_packet_get_data(nativePacket);
  248. }
  249. }
  250. public int Length {
  251. get {
  252. CheckCreated();
  253. return Native.enet_packet_get_length(nativePacket);
  254. }
  255. }
  256. public bool HasReferences {
  257. get {
  258. CheckCreated();
  259. return Native.enet_packet_check_references(nativePacket) != 0;
  260. }
  261. }
  262. internal void CheckCreated()
  263. {
  264. if (nativePacket == IntPtr.Zero)
  265. throw new InvalidOperationException("Packet not created");
  266. }
  267. public void SetFreeCallback(IntPtr callback)
  268. {
  269. CheckCreated();
  270. Native.enet_packet_set_free_callback(nativePacket, callback);
  271. }
  272. public void SetFreeCallback(PacketFreeCallback callback)
  273. {
  274. CheckCreated();
  275. Native.enet_packet_set_free_callback(nativePacket, Marshal.GetFunctionPointerForDelegate(callback));
  276. }
  277. public void Create(byte[] data)
  278. {
  279. if (data == null)
  280. throw new ArgumentNullException("data");
  281. Create(data, data.Length);
  282. }
  283. public void Create(byte[] data, int length)
  284. {
  285. Create(data, length, PacketFlags.None);
  286. }
  287. public void Create(byte[] data, PacketFlags flags)
  288. {
  289. Create(data, data.Length, flags);
  290. }
  291. public void Create(byte[] data, int length, PacketFlags flags)
  292. {
  293. if (data == null)
  294. throw new ArgumentNullException("data");
  295. if (length < 0 || length > data.Length)
  296. throw new ArgumentOutOfRangeException();
  297. nativePacket = Native.enet_packet_create(data, (IntPtr)length, flags);
  298. }
  299. public void Create(IntPtr data, int length, PacketFlags flags)
  300. {
  301. if (data == IntPtr.Zero)
  302. throw new ArgumentNullException("data");
  303. if (length < 0)
  304. throw new ArgumentOutOfRangeException();
  305. nativePacket = Native.enet_packet_create(data, (IntPtr)length, flags);
  306. }
  307. public void Create(byte[] data, int offset, int length, PacketFlags flags)
  308. {
  309. if (data == null)
  310. throw new ArgumentNullException("data");
  311. if (offset < 0 || length < 0 || length > data.Length)
  312. throw new ArgumentOutOfRangeException();
  313. nativePacket = Native.enet_packet_create_offset(data, (IntPtr)length, (IntPtr)offset, flags);
  314. }
  315. public void Create(IntPtr data, int offset, int length, PacketFlags flags)
  316. {
  317. if (data == IntPtr.Zero)
  318. throw new ArgumentNullException("data");
  319. if (offset < 0 || length < 0)
  320. throw new ArgumentOutOfRangeException();
  321. nativePacket = Native.enet_packet_create_offset(data, (IntPtr)length, (IntPtr)offset, flags);
  322. }
  323. public void CopyTo(byte[] destination)
  324. {
  325. if (destination == null)
  326. throw new ArgumentNullException("destination");
  327. Marshal.Copy(Data, destination, 0, Length);
  328. }
  329. }
  330. public class Host : IDisposable
  331. {
  332. private IntPtr nativeHost;
  333. internal IntPtr NativeData {
  334. get {
  335. return nativeHost;
  336. }
  337. set {
  338. nativeHost = value;
  339. }
  340. }
  341. public void Dispose()
  342. {
  343. Dispose(true);
  344. GC.SuppressFinalize(this);
  345. }
  346. protected virtual void Dispose(bool disposing)
  347. {
  348. if (nativeHost != IntPtr.Zero)
  349. {
  350. Native.enet_host_destroy(nativeHost);
  351. nativeHost = IntPtr.Zero;
  352. }
  353. }
  354. ~Host()
  355. {
  356. Dispose(false);
  357. }
  358. public bool IsSet {
  359. get {
  360. return nativeHost != IntPtr.Zero;
  361. }
  362. }
  363. public uint PeersCount {
  364. get {
  365. CheckCreated();
  366. return Native.enet_host_get_peers_count(nativeHost);
  367. }
  368. }
  369. public uint PacketsSent {
  370. get {
  371. CheckCreated();
  372. return Native.enet_host_get_packets_sent(nativeHost);
  373. }
  374. }
  375. public uint PacketsReceived {
  376. get {
  377. CheckCreated();
  378. return Native.enet_host_get_packets_received(nativeHost);
  379. }
  380. }
  381. public uint BytesSent {
  382. get {
  383. CheckCreated();
  384. return Native.enet_host_get_bytes_sent(nativeHost);
  385. }
  386. }
  387. public uint BytesReceived {
  388. get {
  389. CheckCreated();
  390. return Native.enet_host_get_bytes_received(nativeHost);
  391. }
  392. }
  393. internal void CheckCreated()
  394. {
  395. if (nativeHost == IntPtr.Zero)
  396. throw new InvalidOperationException("Host not created");
  397. }
  398. private void CheckChannelLimit(int channelLimit)
  399. {
  400. if (channelLimit < 0 || channelLimit > Library.maxChannelCount)
  401. throw new ArgumentOutOfRangeException("channelLimit");
  402. }
  403. public void Create()
  404. {
  405. Create(null, 1, 0);
  406. }
  407. public void Create(int bufferSize)
  408. {
  409. Create(null, 1, 0, 0, 0, bufferSize);
  410. }
  411. public void Create(Address? address, int peerLimit)
  412. {
  413. Create(address, peerLimit, 0);
  414. }
  415. public void Create(Address? address, int peerLimit, int channelLimit)
  416. {
  417. Create(address, peerLimit, channelLimit, 0, 0, 0);
  418. }
  419. public void Create(int peerLimit, int channelLimit)
  420. {
  421. Create(null, peerLimit, channelLimit, 0, 0, 0);
  422. }
  423. public void Create(int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth)
  424. {
  425. Create(null, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth, 0);
  426. }
  427. public void Create(Address? address, int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth)
  428. {
  429. Create(address, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth, 0);
  430. }
  431. public void Create(Address? address, int peerLimit, int channelLimit, uint incomingBandwidth, uint outgoingBandwidth, int bufferSize)
  432. {
  433. if (nativeHost != IntPtr.Zero)
  434. throw new InvalidOperationException("Host already created");
  435. if (peerLimit < 0 || peerLimit > Library.maxPeers)
  436. throw new ArgumentOutOfRangeException("peerLimit");
  437. CheckChannelLimit(channelLimit);
  438. if (address != null)
  439. {
  440. ENetAddress nativeAddress = address.Value.NativeData;
  441. nativeHost = Native.enet_host_create(ref nativeAddress, (IntPtr)peerLimit, (IntPtr)channelLimit, incomingBandwidth, outgoingBandwidth, bufferSize);
  442. }
  443. else
  444. {
  445. nativeHost = Native.enet_host_create(IntPtr.Zero, (IntPtr)peerLimit, (IntPtr)channelLimit, incomingBandwidth, outgoingBandwidth, bufferSize);
  446. }
  447. if (nativeHost == IntPtr.Zero)
  448. throw new InvalidOperationException("Host creation call failed");
  449. }
  450. public void EnableCompression()
  451. {
  452. CheckCreated();
  453. Native.enet_host_enable_compression(nativeHost);
  454. }
  455. public void PreventConnections(bool state)
  456. {
  457. CheckCreated();
  458. Native.enet_host_prevent_connections(nativeHost, (byte)(state ? 1 : 0));
  459. }
  460. public void Broadcast(byte channelID, ref Packet packet)
  461. {
  462. CheckCreated();
  463. packet.CheckCreated();
  464. Native.enet_host_broadcast(nativeHost, channelID, packet.NativeData);
  465. packet.NativeData = IntPtr.Zero;
  466. }
  467. public void Broadcast(byte channelID, ref Packet packet, Peer excludedPeer)
  468. {
  469. CheckCreated();
  470. packet.CheckCreated();
  471. Native.enet_host_broadcast_exclude(nativeHost, channelID, packet.NativeData, excludedPeer.NativeData);
  472. packet.NativeData = IntPtr.Zero;
  473. }
  474. public void Broadcast(byte channelID, ref Packet packet, Peer[] peers)
  475. {
  476. CheckCreated();
  477. packet.CheckCreated();
  478. if (peers.Length > 0)
  479. {
  480. IntPtr[] nativePeers = ArrayPool.GetPointerBuffer();
  481. int nativeCount = 0;
  482. for (int i = 0; i < peers.Length; i++)
  483. {
  484. if (peers[i].NativeData != IntPtr.Zero)
  485. {
  486. nativePeers[nativeCount] = peers[i].NativeData;
  487. nativeCount++;
  488. }
  489. }
  490. Native.enet_host_broadcast_selective(nativeHost, channelID, packet.NativeData, nativePeers, (IntPtr)nativeCount);
  491. }
  492. packet.NativeData = IntPtr.Zero;
  493. }
  494. public int CheckEvents(out Event @event)
  495. {
  496. CheckCreated();
  497. int result = Native.enet_host_check_events(nativeHost, out ENetEvent nativeEvent);
  498. if (result <= 0)
  499. {
  500. @event = default;
  501. return result;
  502. }
  503. @event = new Event(nativeEvent);
  504. return result;
  505. }
  506. public Peer Connect(Address address)
  507. {
  508. return Connect(address, 0, 0);
  509. }
  510. public Peer Connect(Address address, int channelLimit)
  511. {
  512. return Connect(address, channelLimit, 0);
  513. }
  514. public Peer Connect(Address address, int channelLimit, uint data)
  515. {
  516. CheckCreated();
  517. CheckChannelLimit(channelLimit);
  518. ENetAddress nativeAddress = address.NativeData;
  519. Peer peer = new Peer(Native.enet_host_connect(nativeHost, ref nativeAddress, (IntPtr)channelLimit, data));
  520. if (peer.NativeData == IntPtr.Zero)
  521. throw new InvalidOperationException("Host connect call failed");
  522. return peer;
  523. }
  524. public int Service(int timeout, out Event @event)
  525. {
  526. if (timeout < 0)
  527. throw new ArgumentOutOfRangeException("timeout");
  528. CheckCreated();
  529. int result = Native.enet_host_service(nativeHost, out ENetEvent nativeEvent, (uint)timeout);
  530. if (result <= 0)
  531. {
  532. @event = default;
  533. return result;
  534. }
  535. @event = new Event(nativeEvent);
  536. return result;
  537. }
  538. public void SetBandwidthLimit(uint incomingBandwidth, uint outgoingBandwidth)
  539. {
  540. CheckCreated();
  541. Native.enet_host_bandwidth_limit(nativeHost, incomingBandwidth, outgoingBandwidth);
  542. }
  543. public void SetChannelLimit(int channelLimit)
  544. {
  545. CheckCreated();
  546. CheckChannelLimit(channelLimit);
  547. Native.enet_host_channel_limit(nativeHost, (IntPtr)channelLimit);
  548. }
  549. public void Flush()
  550. {
  551. CheckCreated();
  552. Native.enet_host_flush(nativeHost);
  553. }
  554. }
  555. public struct Peer
  556. {
  557. private IntPtr nativePeer;
  558. private readonly uint nativeID;
  559. internal IntPtr NativeData {
  560. get {
  561. return nativePeer;
  562. }
  563. set {
  564. nativePeer = value;
  565. }
  566. }
  567. internal Peer(IntPtr peer)
  568. {
  569. nativePeer = peer;
  570. nativeID = nativePeer != IntPtr.Zero ? Native.enet_peer_get_id(nativePeer) : 0;
  571. }
  572. public bool IsSet {
  573. get {
  574. return nativePeer != IntPtr.Zero;
  575. }
  576. }
  577. public uint ID {
  578. get {
  579. return nativeID;
  580. }
  581. }
  582. public string IP {
  583. get {
  584. CheckCreated();
  585. byte[] ip = ArrayPool.GetByteBuffer();
  586. if (Native.enet_peer_get_ip(nativePeer, ip, (IntPtr)ip.Length) == 0)
  587. return Encoding.ASCII.GetString(ip, 0, ip.StringLength());
  588. else
  589. return String.Empty;
  590. }
  591. }
  592. public ushort Port {
  593. get {
  594. CheckCreated();
  595. return Native.enet_peer_get_port(nativePeer);
  596. }
  597. }
  598. public uint MTU {
  599. get {
  600. CheckCreated();
  601. return Native.enet_peer_get_mtu(nativePeer);
  602. }
  603. }
  604. public PeerState State {
  605. get {
  606. return nativePeer == IntPtr.Zero ? PeerState.Uninitialized : Native.enet_peer_get_state(nativePeer);
  607. }
  608. }
  609. public uint RoundTripTime {
  610. get {
  611. CheckCreated();
  612. return Native.enet_peer_get_rtt(nativePeer);
  613. }
  614. }
  615. public uint LastSendTime {
  616. get {
  617. CheckCreated();
  618. return Native.enet_peer_get_lastsendtime(nativePeer);
  619. }
  620. }
  621. public uint LastReceiveTime {
  622. get {
  623. CheckCreated();
  624. return Native.enet_peer_get_lastreceivetime(nativePeer);
  625. }
  626. }
  627. public ulong PacketsSent {
  628. get {
  629. CheckCreated();
  630. return Native.enet_peer_get_packets_sent(nativePeer);
  631. }
  632. }
  633. public ulong PacketsLost {
  634. get {
  635. CheckCreated();
  636. return Native.enet_peer_get_packets_lost(nativePeer);
  637. }
  638. }
  639. public ulong BytesSent {
  640. get {
  641. CheckCreated();
  642. return Native.enet_peer_get_bytes_sent(nativePeer);
  643. }
  644. }
  645. public ulong BytesReceived {
  646. get {
  647. CheckCreated();
  648. return Native.enet_peer_get_bytes_received(nativePeer);
  649. }
  650. }
  651. public IntPtr Data {
  652. get {
  653. CheckCreated();
  654. return Native.enet_peer_get_data(nativePeer);
  655. }
  656. set {
  657. CheckCreated();
  658. Native.enet_peer_set_data(nativePeer, value);
  659. }
  660. }
  661. internal void CheckCreated()
  662. {
  663. if (nativePeer == IntPtr.Zero)
  664. throw new InvalidOperationException("Peer not created");
  665. }
  666. public void ConfigureThrottle(uint interval, uint acceleration, uint deceleration, uint threshold)
  667. {
  668. CheckCreated();
  669. Native.enet_peer_throttle_configure(nativePeer, interval, acceleration, deceleration, threshold);
  670. }
  671. public bool Send(byte channelID, ref Packet packet)
  672. {
  673. CheckCreated();
  674. packet.CheckCreated();
  675. return Native.enet_peer_send(nativePeer, channelID, packet.NativeData) == 0;
  676. }
  677. // Added by Coburn. This version returns either 0 if the send was successful,
  678. // or the ENET return code if not. Sometimes a bool is not enough to determine
  679. // the root cause of the issue.
  680. public int SendAndReturnStatusCode(byte channelID, ref Packet packet)
  681. {
  682. CheckCreated();
  683. packet.CheckCreated();
  684. return Native.enet_peer_send(nativePeer, channelID, packet.NativeData);
  685. }
  686. public bool Receive(out byte channelID, out Packet packet)
  687. {
  688. CheckCreated();
  689. IntPtr nativePacket = Native.enet_peer_receive(nativePeer, out channelID);
  690. if (nativePacket != IntPtr.Zero)
  691. {
  692. packet = new Packet(nativePacket);
  693. return true;
  694. }
  695. packet = default;
  696. return false;
  697. }
  698. public void Ping()
  699. {
  700. CheckCreated();
  701. Native.enet_peer_ping(nativePeer);
  702. }
  703. public void PingInterval(uint interval)
  704. {
  705. CheckCreated();
  706. Native.enet_peer_ping_interval(nativePeer, interval);
  707. }
  708. public void Timeout(uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum)
  709. {
  710. CheckCreated();
  711. Native.enet_peer_timeout(nativePeer, timeoutLimit, timeoutMinimum, timeoutMaximum);
  712. }
  713. public void Disconnect(uint data)
  714. {
  715. CheckCreated();
  716. Native.enet_peer_disconnect(nativePeer, data);
  717. }
  718. public void DisconnectNow(uint data)
  719. {
  720. CheckCreated();
  721. Native.enet_peer_disconnect_now(nativePeer, data);
  722. }
  723. public void DisconnectLater(uint data)
  724. {
  725. CheckCreated();
  726. Native.enet_peer_disconnect_later(nativePeer, data);
  727. }
  728. public void Reset()
  729. {
  730. CheckCreated();
  731. Native.enet_peer_reset(nativePeer);
  732. }
  733. }
  734. public static class Extensions
  735. {
  736. public static int StringLength(this byte[] data)
  737. {
  738. if (data == null)
  739. throw new ArgumentNullException("data");
  740. int i;
  741. for (i = 0; i < data.Length && data[i] != 0; i++) ;
  742. return i;
  743. }
  744. }
  745. public static class Library
  746. {
  747. public const uint maxChannelCount = 0xFF;
  748. public const uint maxPeers = 0xFFF;
  749. public const uint maxPacketSize = 32 * 1024 * 1024;
  750. public const uint throttleScale = 32;
  751. public const uint throttleAcceleration = 2;
  752. public const uint throttleDeceleration = 2;
  753. public const uint throttleInterval = 5000;
  754. public const uint timeoutLimit = 32;
  755. public const uint timeoutMinimum = 5000;
  756. public const uint timeoutMaximum = 30000;
  757. public const uint version = (2 << 16) | (3 << 8) | (0);
  758. public static bool Initialize()
  759. {
  760. return Native.enet_initialize() == 0;
  761. }
  762. public static bool Initialize(Callbacks inits)
  763. {
  764. return Native.enet_initialize_with_callbacks(version, inits.NativeData) == 0;
  765. }
  766. public static void Deinitialize()
  767. {
  768. Native.enet_deinitialize();
  769. }
  770. public static uint Time {
  771. get {
  772. return Native.enet_time_get();
  773. }
  774. }
  775. }
  776. [SuppressUnmanagedCodeSecurity]
  777. internal static class Native
  778. {
  779. #if __IOS__ || UNITY_IOS && !UNITY_EDITOR
  780. // iOS
  781. private const string nativeLibrary = "__Internal";
  782. #elif __APPLE__ || UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
  783. // MacOS
  784. // Custom ENet Repo builds as libenet.bundle; make sure it's the same.
  785. private const string nativeLibrary = "libenet";
  786. #else
  787. // Assume everything else, Windows et al...
  788. // This might be interesting if someone's building for Nintendo Switch or whatnot...
  789. private const string nativeLibrary = "enet";
  790. #endif
  791. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  792. internal static extern int enet_initialize();
  793. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  794. internal static extern int enet_initialize_with_callbacks(uint version, ENetCallbacks inits);
  795. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  796. internal static extern void enet_deinitialize();
  797. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  798. internal static extern uint enet_time_get();
  799. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  800. internal static extern int enet_address_set_host_ip(ref ENetAddress address, string ip);
  801. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  802. internal static extern int enet_address_set_host(ref ENetAddress address, string hostName);
  803. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  804. internal static extern int enet_address_get_host_ip(ENetAddress address, StringBuilder ip, IntPtr ipLength);
  805. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
  806. internal static extern int enet_address_get_host(ENetAddress address, StringBuilder hostName, IntPtr nameLength);
  807. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  808. internal static extern IntPtr enet_packet_create(byte[] data, IntPtr dataLength, PacketFlags flags);
  809. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  810. internal static extern IntPtr enet_packet_create(IntPtr data, IntPtr dataLength, PacketFlags flags);
  811. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  812. internal static extern IntPtr enet_packet_create_offset(byte[] data, IntPtr dataLength, IntPtr dataOffset, PacketFlags flags);
  813. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  814. internal static extern IntPtr enet_packet_create_offset(IntPtr data, IntPtr dataLength, IntPtr dataOffset, PacketFlags flags);
  815. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  816. internal static extern int enet_packet_check_references(IntPtr packet);
  817. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  818. internal static extern IntPtr enet_packet_get_data(IntPtr packet);
  819. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  820. internal static extern int enet_packet_get_length(IntPtr packet);
  821. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  822. internal static extern void enet_packet_set_free_callback(IntPtr packet, IntPtr callback);
  823. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  824. internal static extern void enet_packet_dispose(IntPtr packet);
  825. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  826. internal static extern IntPtr enet_host_create(ref ENetAddress address, IntPtr peerLimit, IntPtr channelLimit, uint incomingBandwidth, uint outgoingBandwidth, int bufferSize);
  827. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  828. internal static extern IntPtr enet_host_create(IntPtr address, IntPtr peerLimit, IntPtr channelLimit, uint incomingBandwidth, uint outgoingBandwidth, int bufferSize);
  829. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  830. internal static extern IntPtr enet_host_connect(IntPtr host, ref ENetAddress address, IntPtr channelCount, uint data);
  831. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  832. internal static extern void enet_host_broadcast(IntPtr host, byte channelID, IntPtr packet);
  833. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  834. internal static extern void enet_host_broadcast_exclude(IntPtr host, byte channelID, IntPtr packet, IntPtr excludedPeer);
  835. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  836. internal static extern void enet_host_broadcast_selective(IntPtr host, byte channelID, IntPtr packet, IntPtr[] peers, IntPtr peersLength);
  837. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  838. internal static extern int enet_host_service(IntPtr host, out ENetEvent @event, uint timeout);
  839. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  840. internal static extern int enet_host_check_events(IntPtr host, out ENetEvent @event);
  841. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  842. internal static extern void enet_host_channel_limit(IntPtr host, IntPtr channelLimit);
  843. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  844. internal static extern void enet_host_bandwidth_limit(IntPtr host, uint incomingBandwidth, uint outgoingBandwidth);
  845. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  846. internal static extern uint enet_host_get_peers_count(IntPtr host);
  847. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  848. internal static extern uint enet_host_get_packets_sent(IntPtr host);
  849. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  850. internal static extern uint enet_host_get_packets_received(IntPtr host);
  851. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  852. internal static extern uint enet_host_get_bytes_sent(IntPtr host);
  853. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  854. internal static extern uint enet_host_get_bytes_received(IntPtr host);
  855. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  856. internal static extern void enet_host_flush(IntPtr host);
  857. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  858. internal static extern void enet_host_destroy(IntPtr host);
  859. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  860. internal static extern void enet_host_enable_compression(IntPtr host);
  861. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  862. internal static extern void enet_host_prevent_connections(IntPtr host, byte state);
  863. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  864. internal static extern void enet_peer_throttle_configure(IntPtr peer, uint interval, uint acceleration, uint deceleration, uint threshold);
  865. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  866. internal static extern uint enet_peer_get_id(IntPtr peer);
  867. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  868. internal static extern int enet_peer_get_ip(IntPtr peer, byte[] ip, IntPtr ipLength);
  869. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  870. internal static extern ushort enet_peer_get_port(IntPtr peer);
  871. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  872. internal static extern uint enet_peer_get_mtu(IntPtr peer);
  873. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  874. internal static extern PeerState enet_peer_get_state(IntPtr peer);
  875. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  876. internal static extern uint enet_peer_get_rtt(IntPtr peer);
  877. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  878. internal static extern uint enet_peer_get_lastsendtime(IntPtr peer);
  879. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  880. internal static extern uint enet_peer_get_lastreceivetime(IntPtr peer);
  881. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  882. internal static extern ulong enet_peer_get_packets_sent(IntPtr peer);
  883. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  884. internal static extern ulong enet_peer_get_packets_lost(IntPtr peer);
  885. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  886. internal static extern ulong enet_peer_get_bytes_sent(IntPtr peer);
  887. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  888. internal static extern ulong enet_peer_get_bytes_received(IntPtr peer);
  889. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  890. internal static extern IntPtr enet_peer_get_data(IntPtr peer);
  891. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  892. internal static extern void enet_peer_set_data(IntPtr peer, IntPtr data);
  893. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  894. internal static extern int enet_peer_send(IntPtr peer, byte channelID, IntPtr packet);
  895. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  896. internal static extern IntPtr enet_peer_receive(IntPtr peer, out byte channelID);
  897. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  898. internal static extern void enet_peer_ping(IntPtr peer);
  899. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  900. internal static extern void enet_peer_ping_interval(IntPtr peer, uint pingInterval);
  901. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  902. internal static extern void enet_peer_timeout(IntPtr peer, uint timeoutLimit, uint timeoutMinimum, uint timeoutMaximum);
  903. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  904. internal static extern void enet_peer_disconnect(IntPtr peer, uint data);
  905. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  906. internal static extern void enet_peer_disconnect_now(IntPtr peer, uint data);
  907. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  908. internal static extern void enet_peer_disconnect_later(IntPtr peer, uint data);
  909. [DllImport(nativeLibrary, CallingConvention = CallingConvention.Cdecl)]
  910. internal static extern void enet_peer_reset(IntPtr peer);
  911. }
  912. }