PhotonPing.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // ----------------------------------------------------------------------------
  2. // <copyright file="PhotonPing.cs" company="Exit Games GmbH">
  3. // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH
  4. // </copyright>
  5. // <summary>
  6. // This file includes various PhotonPing implementations for different APIs,
  7. // platforms and protocols.
  8. // The RegionPinger class is the instance which selects the Ping implementation
  9. // to use.
  10. // </summary>
  11. // <author>developer@exitgames.com</author>
  12. // ----------------------------------------------------------------------------
  13. namespace Photon.Realtime
  14. {
  15. using System;
  16. using System.Collections;
  17. using System.Threading;
  18. #if NETFX_CORE
  19. using System.Diagnostics;
  20. using Windows.Foundation;
  21. using Windows.Networking;
  22. using Windows.Networking.Sockets;
  23. using Windows.Storage.Streams;
  24. #endif
  25. #if !NO_SOCKET && !NETFX_CORE
  26. using System.Collections.Generic;
  27. using System.Diagnostics;
  28. using System.Net.Sockets;
  29. #endif
  30. #if UNITY_WEBGL
  31. // import UnityWebRequest
  32. using UnityEngine.Networking;
  33. #endif
  34. /// <summary>
  35. /// Abstract implementation of PhotonPing, ase for pinging servers to find the "Best Region".
  36. /// </summary>
  37. public abstract class PhotonPing : IDisposable
  38. {
  39. /// <summary>Caches the last exception/error message, if any.</summary>
  40. public string DebugString = "";
  41. /// <summary>True of the ping was successful.</summary>
  42. public bool Successful;
  43. /// <summary>True if there was any result.</summary>
  44. protected internal bool GotResult;
  45. /// <summary>Length of a ping.</summary>
  46. protected internal int PingLength = 13;
  47. /// <summary>Bytes to send in a (Photon UDP) ping.</summary>
  48. protected internal byte[] PingBytes = new byte[] { 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x7d, 0x00 };
  49. /// <summary>Randomized number to identify a ping.</summary>
  50. protected internal byte PingId;
  51. private static readonly System.Random RandomIdProvider = new System.Random();
  52. /// <summary>Begins sending a ping.</summary>
  53. public virtual bool StartPing(string ip)
  54. {
  55. throw new NotImplementedException();
  56. }
  57. /// <summary>Check if done.</summary>
  58. public virtual bool Done()
  59. {
  60. throw new NotImplementedException();
  61. }
  62. /// <summary>Dispose of this ping.</summary>
  63. public virtual void Dispose()
  64. {
  65. throw new NotImplementedException();
  66. }
  67. /// <summary>Initialize this ping (GotResult, Successful, PingId).</summary>
  68. protected internal void Init()
  69. {
  70. this.GotResult = false;
  71. this.Successful = false;
  72. this.PingId = (byte)(RandomIdProvider.Next(255));
  73. }
  74. }
  75. #if !NETFX_CORE && !NO_SOCKET
  76. /// <summary>Uses C# Socket class from System.Net.Sockets (as Unity usually does).</summary>
  77. /// <remarks>Incompatible with Windows 8 Store/Phone API.</remarks>
  78. public class PingMono : PhotonPing
  79. {
  80. private Socket sock;
  81. /// <summary>
  82. /// Sends a "Photon Ping" to a server.
  83. /// </summary>
  84. /// <param name="ip">Address in IPv4 or IPv6 format. An address containing a '.' will be interpreted as IPv4.</param>
  85. /// <returns>True if the Photon Ping could be sent.</returns>
  86. public override bool StartPing(string ip)
  87. {
  88. this.Init();
  89. try
  90. {
  91. if (this.sock == null)
  92. {
  93. if (ip.Contains("."))
  94. {
  95. this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  96. }
  97. else
  98. {
  99. this.sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
  100. }
  101. this.sock.ReceiveTimeout = 5000;
  102. int port = (RegionHandler.PortToPingOverride != 0) ? RegionHandler.PortToPingOverride : 5055;
  103. this.sock.Connect(ip, port);
  104. }
  105. this.PingBytes[this.PingBytes.Length - 1] = this.PingId;
  106. this.sock.Send(this.PingBytes);
  107. this.PingBytes[this.PingBytes.Length - 1] = (byte)(this.PingId+1); // this buffer is re-used for the result/receive. invalidate the result now.
  108. }
  109. catch (Exception e)
  110. {
  111. this.sock = null;
  112. System.Diagnostics.Debug.WriteLine(e.ToString());
  113. // bubble up
  114. throw;
  115. }
  116. return false;
  117. }
  118. /// <summary>Check if done.</summary>
  119. public override bool Done()
  120. {
  121. if (this.GotResult || this.sock == null)
  122. {
  123. return true; // this just indicates the ping is no longer waiting. this.Successful value defines if the roundtrip completed
  124. }
  125. int read = 0;
  126. try
  127. {
  128. if (!this.sock.Poll(0, SelectMode.SelectRead))
  129. {
  130. return false;
  131. }
  132. read = this.sock.Receive(this.PingBytes, SocketFlags.None);
  133. }
  134. catch (Exception ex)
  135. {
  136. if (this.sock != null)
  137. {
  138. this.sock.Close();
  139. this.sock = null;
  140. }
  141. this.DebugString += " Exception of socket! " + ex.GetType() + " ";
  142. return true; // this just indicates the ping is no longer waiting. this.Successful value defines if the roundtrip completed
  143. }
  144. bool replyMatch = this.PingBytes[this.PingBytes.Length - 1] == this.PingId && read == this.PingLength;
  145. if (!replyMatch)
  146. {
  147. this.DebugString += " ReplyMatch is false! ";
  148. }
  149. this.Successful = replyMatch;
  150. this.GotResult = true;
  151. return true;
  152. }
  153. /// <summary>Dispose of this ping.</summary>
  154. public override void Dispose()
  155. {
  156. if (this.sock == null) { return; }
  157. try
  158. {
  159. this.sock.Close();
  160. }
  161. catch
  162. {
  163. }
  164. this.sock = null;
  165. }
  166. }
  167. #endif
  168. #if NETFX_CORE
  169. /// <summary>Windows store API implementation of PhotonPing, based on DatagramSocket for UDP.</summary>
  170. public class PingWindowsStore : PhotonPing
  171. {
  172. private DatagramSocket sock;
  173. private readonly object syncer = new object();
  174. public override bool StartPing(string host)
  175. {
  176. lock (this.syncer)
  177. {
  178. this.Init();
  179. int port = (RegionHandler.PortToPingOverride != 0) ? RegionHandler.PortToPingOverride : 5055;
  180. EndpointPair endPoint = new EndpointPair(null, string.Empty, new HostName(host), port.ToString());
  181. this.sock = new DatagramSocket();
  182. this.sock.MessageReceived += this.OnMessageReceived;
  183. IAsyncAction result = this.sock.ConnectAsync(endPoint);
  184. result.Completed = this.OnConnected;
  185. this.DebugString += " End StartPing";
  186. return true;
  187. }
  188. }
  189. /// <summary>Check if done.</summary>
  190. public override bool Done()
  191. {
  192. lock (this.syncer)
  193. {
  194. return this.GotResult || this.sock == null; // this just indicates the ping is no longer waiting. this.Successful value defines if the roundtrip completed
  195. }
  196. }
  197. /// <summary>Dispose of this ping.</summary>
  198. public override void Dispose()
  199. {
  200. lock (this.syncer)
  201. {
  202. this.sock = null;
  203. }
  204. }
  205. private void OnConnected(IAsyncAction asyncinfo, AsyncStatus asyncstatus)
  206. {
  207. lock (this.syncer)
  208. {
  209. if (asyncinfo.AsTask().IsCompleted && !asyncinfo.AsTask().IsFaulted && this.sock != null && this.sock.Information.RemoteAddress != null)
  210. {
  211. this.PingBytes[this.PingBytes.Length - 1] = this.PingId;
  212. DataWriter writer;
  213. writer = new DataWriter(this.sock.OutputStream);
  214. writer.WriteBytes(this.PingBytes);
  215. DataWriterStoreOperation res = writer.StoreAsync();
  216. res.AsTask().Wait(100);
  217. this.PingBytes[this.PingBytes.Length - 1] = (byte)(this.PingId + 1); // this buffer is re-used for the result/receive. invalidate the result now.
  218. writer.DetachStream();
  219. writer.Dispose();
  220. }
  221. else
  222. {
  223. this.sock = null; // will cause Done() to return true but this.Successful defines if the roundtrip completed
  224. }
  225. }
  226. }
  227. private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
  228. {
  229. lock (this.syncer)
  230. {
  231. DataReader reader = null;
  232. try
  233. {
  234. reader = args.GetDataReader();
  235. uint receivedByteCount = reader.UnconsumedBufferLength;
  236. if (receivedByteCount > 0)
  237. {
  238. byte[] resultBytes = new byte[receivedByteCount];
  239. reader.ReadBytes(resultBytes);
  240. //TODO: check result bytes!
  241. this.Successful = receivedByteCount == this.PingLength && resultBytes[resultBytes.Length - 1] == this.PingId;
  242. this.GotResult = true;
  243. }
  244. }
  245. catch
  246. {
  247. // TODO: handle error
  248. }
  249. }
  250. }
  251. }
  252. #endif
  253. #if NATIVE_SOCKETS
  254. /// <summary>Abstract base class to provide proper resource management for the below native ping implementations</summary>
  255. public abstract class PingNative : PhotonPing
  256. {
  257. // Native socket states - according to EnetConnect.h state definitions
  258. protected enum NativeSocketState : byte
  259. {
  260. Disconnected = 0,
  261. Connecting = 1,
  262. Connected = 2,
  263. ConnectionError = 3,
  264. SendError = 4,
  265. ReceiveError = 5,
  266. Disconnecting = 6
  267. }
  268. protected IntPtr pConnectionHandler = IntPtr.Zero;
  269. ~PingNative()
  270. {
  271. Dispose();
  272. }
  273. }
  274. /// <summary>Uses dynamic linked native Photon socket library via DllImport("PhotonSocketPlugin") attribute (as done by Unity Android and Unity PS3).</summary>
  275. public class PingNativeDynamic : PingNative
  276. {
  277. public override bool StartPing(string ip)
  278. {
  279. lock (SocketUdpNativeDynamic.syncer)
  280. {
  281. base.Init();
  282. if(pConnectionHandler == IntPtr.Zero)
  283. {
  284. pConnectionHandler = SocketUdpNativeDynamic.egconnect(ip);
  285. SocketUdpNativeDynamic.egservice(pConnectionHandler);
  286. byte state = SocketUdpNativeDynamic.eggetState(pConnectionHandler);
  287. while (state == (byte) NativeSocketState.Connecting)
  288. {
  289. SocketUdpNativeDynamic.egservice(pConnectionHandler);
  290. state = SocketUdpNativeDynamic.eggetState(pConnectionHandler);
  291. }
  292. }
  293. PingBytes[PingBytes.Length - 1] = PingId;
  294. SocketUdpNativeDynamic.egsend(pConnectionHandler, PingBytes, PingBytes.Length);
  295. SocketUdpNativeDynamic.egservice(pConnectionHandler);
  296. PingBytes[PingBytes.Length - 1] = (byte) (PingId - 1);
  297. return true;
  298. }
  299. }
  300. public override bool Done()
  301. {
  302. lock (SocketUdpNativeDynamic.syncer)
  303. {
  304. if (this.GotResult || pConnectionHandler == IntPtr.Zero)
  305. {
  306. return true;
  307. }
  308. int available = SocketUdpNativeDynamic.egservice(pConnectionHandler);
  309. if (available < PingLength)
  310. {
  311. return false;
  312. }
  313. int pingBytesLength = PingBytes.Length;
  314. int bytesInRemainginDatagrams = SocketUdpNativeDynamic.egread(pConnectionHandler, PingBytes, ref pingBytesLength);
  315. this.Successful = (PingBytes != null && PingBytes[PingBytes.Length - 1] == PingId);
  316. //Debug.Log("Successful: " + this.Successful + " bytesInRemainginDatagrams: " + bytesInRemainginDatagrams + " PingId: " + PingId);
  317. this.GotResult = true;
  318. return true;
  319. }
  320. }
  321. public override void Dispose()
  322. {
  323. lock (SocketUdpNativeDynamic.syncer)
  324. {
  325. if (this.pConnectionHandler != IntPtr.Zero)
  326. SocketUdpNativeDynamic.egdisconnect(this.pConnectionHandler);
  327. this.pConnectionHandler = IntPtr.Zero;
  328. }
  329. GC.SuppressFinalize(this);
  330. }
  331. }
  332. #if NATIVE_SOCKETS && NATIVE_SOCKETS_STATIC
  333. /// <summary>Uses static linked native Photon socket library via DllImport("__Internal") attribute (as done by Unity iOS and Unity Switch).</summary>
  334. public class PingNativeStatic : PingNative
  335. {
  336. public override bool StartPing(string ip)
  337. {
  338. base.Init();
  339. lock (SocketUdpNativeStatic.syncer)
  340. {
  341. if(pConnectionHandler == IntPtr.Zero)
  342. {
  343. pConnectionHandler = SocketUdpNativeStatic.egconnect(ip);
  344. SocketUdpNativeStatic.egservice(pConnectionHandler);
  345. byte state = SocketUdpNativeStatic.eggetState(pConnectionHandler);
  346. while (state == (byte) NativeSocketState.Connecting)
  347. {
  348. SocketUdpNativeStatic.egservice(pConnectionHandler);
  349. state = SocketUdpNativeStatic.eggetState(pConnectionHandler);
  350. Thread.Sleep(0); // suspending execution for a moment is critical on Switch for the OS to update the socket
  351. }
  352. }
  353. PingBytes[PingBytes.Length - 1] = PingId;
  354. SocketUdpNativeStatic.egsend(pConnectionHandler, PingBytes, PingBytes.Length);
  355. SocketUdpNativeStatic.egservice(pConnectionHandler);
  356. PingBytes[PingBytes.Length - 1] = (byte) (PingId - 1);
  357. return true;
  358. }
  359. }
  360. public override bool Done()
  361. {
  362. lock (SocketUdpNativeStatic.syncer)
  363. {
  364. if (this.GotResult || pConnectionHandler == IntPtr.Zero)
  365. {
  366. return true;
  367. }
  368. int available = SocketUdpNativeStatic.egservice(pConnectionHandler);
  369. if (available < PingLength)
  370. {
  371. return false;
  372. }
  373. int pingBytesLength = PingBytes.Length;
  374. int bytesInRemainginDatagrams = SocketUdpNativeStatic.egread(pConnectionHandler, PingBytes, ref pingBytesLength);
  375. this.Successful = (PingBytes != null && PingBytes[PingBytes.Length - 1] == PingId);
  376. //Debug.Log("Successful: " + this.Successful + " bytesInRemainginDatagrams: " + bytesInRemainginDatagrams + " PingId: " + PingId);
  377. this.GotResult = true;
  378. return true;
  379. }
  380. }
  381. public override void Dispose()
  382. {
  383. lock (SocketUdpNativeStatic.syncer)
  384. {
  385. if (pConnectionHandler != IntPtr.Zero)
  386. SocketUdpNativeStatic.egdisconnect(pConnectionHandler);
  387. pConnectionHandler = IntPtr.Zero;
  388. }
  389. GC.SuppressFinalize(this);
  390. }
  391. }
  392. #endif
  393. #endif
  394. #if UNITY_WEBGL
  395. public class PingHttp : PhotonPing
  396. {
  397. private UnityWebRequest webRequest;
  398. public override bool StartPing(string address)
  399. {
  400. base.Init();
  401. address = "https://" + address + "/photon/m/?ping&r=" + UnityEngine.Random.Range(0, 10000);
  402. this.webRequest = UnityWebRequest.Get(address);
  403. this.webRequest.SendWebRequest();
  404. return true;
  405. }
  406. public override bool Done()
  407. {
  408. if (this.webRequest.isDone)
  409. {
  410. Successful = true;
  411. return true;
  412. }
  413. return false;
  414. }
  415. public override void Dispose()
  416. {
  417. this.webRequest.Dispose();
  418. }
  419. }
  420. #endif
  421. }