ENet.cs 36 KB

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