ENet.cs 42 KB

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