SocketWebTcp.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. #if UNITY_WEBGL || WEBSOCKET || WEBSOCKET_PROXYCONFIG
  2. // --------------------------------------------------------------------------------------------------------------------
  3. // <copyright file="SocketWebTcp.cs" company="Exit Games GmbH">
  4. // Copyright (c) Exit Games GmbH. All rights reserved.
  5. // </copyright>
  6. // <summary>
  7. // Internal class to encapsulate the network i/o functionality for the realtime library.
  8. // </summary>
  9. // <author>developer@exitgames.com</author>
  10. // --------------------------------------------------------------------------------------------------------------------
  11. namespace ExitGames.Client.Photon
  12. {
  13. using System;
  14. using System.Collections;
  15. using UnityEngine;
  16. using UnityEngine.Scripting;
  17. using SupportClassPun = SupportClass;
  18. /// <summary>
  19. /// Yield Instruction to Wait for real seconds. Very important to keep connection working if Time.TimeScale is altered, we still want accurate network events
  20. /// </summary>
  21. public sealed class WaitForRealSeconds : CustomYieldInstruction
  22. {
  23. private readonly float _endTime;
  24. public override bool keepWaiting
  25. {
  26. get { return this._endTime > Time.realtimeSinceStartup; }
  27. }
  28. public WaitForRealSeconds(float seconds)
  29. {
  30. this._endTime = Time.realtimeSinceStartup + seconds;
  31. }
  32. }
  33. /// <summary>
  34. /// Internal class to encapsulate the network i/o functionality for the realtime libary.
  35. /// </summary>
  36. public class SocketWebTcp : IPhotonSocket, IDisposable
  37. {
  38. private WebSocket sock;
  39. private readonly object syncer = new object();
  40. [Preserve]
  41. public SocketWebTcp(PeerBase npeer) : base(npeer)
  42. {
  43. this.ServerAddress = npeer.ServerAddress;
  44. this.ProxyServerAddress = npeer.ProxyServerAddress;
  45. if (this.ReportDebugOfLevel(DebugLevel.INFO))
  46. {
  47. this.Listener.DebugReturn(DebugLevel.INFO, "new SocketWebTcp() for Unity. Server: " + this.ServerAddress + (String.IsNullOrEmpty(this.ProxyServerAddress) ? "" : ", Proxy: " + this.ProxyServerAddress));
  48. }
  49. //this.Protocol = ConnectionProtocol.WebSocket;
  50. this.PollReceive = false;
  51. }
  52. public void Dispose()
  53. {
  54. this.State = PhotonSocketState.Disconnecting;
  55. if (this.sock != null)
  56. {
  57. try
  58. {
  59. if (this.sock.Connected)
  60. {
  61. this.sock.Close();
  62. }
  63. }
  64. catch (Exception ex)
  65. {
  66. this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in SocketWebTcp.Dispose(): " + ex);
  67. }
  68. }
  69. this.sock = null;
  70. this.State = PhotonSocketState.Disconnected;
  71. }
  72. GameObject websocketConnectionObject;
  73. public override bool Connect()
  74. {
  75. //bool baseOk = base.Connect();
  76. //if (!baseOk)
  77. //{
  78. // return false;
  79. //}
  80. this.State = PhotonSocketState.Connecting;
  81. if (this.websocketConnectionObject != null)
  82. {
  83. UnityEngine.Object.Destroy(this.websocketConnectionObject);
  84. }
  85. this.websocketConnectionObject = new GameObject("websocketConnectionObject");
  86. MonoBehaviour mb = this.websocketConnectionObject.AddComponent<MonoBehaviourExt>();
  87. this.websocketConnectionObject.hideFlags = HideFlags.HideInHierarchy;
  88. UnityEngine.Object.DontDestroyOnLoad(this.websocketConnectionObject);
  89. this.ConnectAddress += "&IPv6"; // this makes the Photon Server return a host name for the next server (NS points to MS and MS points to GS)
  90. // earlier, we read the proxy address/scheme and failed to connect entirely, if that wasn't successful...
  91. // it was either successful (using the resulting proxy address) or no connect at all...
  92. // we want:
  93. // WITH support: fail if the scheme is wrong or use it if possible
  94. // WITHOUT support: use proxy address, if it's a direct value (not a scheme we provide) or fail if it's a scheme
  95. string proxyServerAddress;
  96. if (!this.ReadProxyConfigScheme(this.ProxyServerAddress, this.ServerAddress, out proxyServerAddress))
  97. {
  98. this.Listener.DebugReturn(DebugLevel.INFO, "ReadProxyConfigScheme() failed. Using no proxy.");
  99. }
  100. try
  101. {
  102. this.sock = new WebSocket(new Uri(this.ConnectAddress), proxyServerAddress, this.SerializationProtocol);
  103. this.sock.DebugReturn = (DebugLevel l, string s) =>
  104. {
  105. if (this.State != PhotonSocketState.Disconnected)
  106. {
  107. this.Listener.DebugReturn(l, this.State + " " + s);
  108. }
  109. };
  110. this.sock.Connect();
  111. mb.StartCoroutine(this.ReceiveLoop());
  112. return true;
  113. }
  114. catch (Exception e)
  115. {
  116. this.Listener.DebugReturn(DebugLevel.ERROR, "SocketWebTcp.Connect() caught exception: " + e);
  117. return false;
  118. }
  119. }
  120. /// <summary>
  121. /// Attempts to read a proxy configuration defined by a address prefix. Only available to Industries Circle members on demand.
  122. /// </summary>
  123. /// <remarks>
  124. /// Extended proxy support is available to Industries Circle members. Where available, proxy addresses may be defined as 'auto:', 'pac:' or 'system:'.
  125. /// In all other cases, the proxy address is used as is and fails to read configs (if one of the listed schemes is used).
  126. ///
  127. /// Requires file ProxyAutoConfig.cs and compile define: WEBSOCKET_PROXYCONFIG_SUPPORT.
  128. /// </remarks>
  129. /// <param name="proxyAddress">Proxy address from the server configuration.</param>
  130. /// <param name="url">Url to connect to (one of the Photon servers).</param>
  131. /// <param name="proxyUrl">Resulting proxy URL to use.</param>
  132. /// <returns>False if there is some error and the resulting proxy address should not be used.</returns>
  133. private bool ReadProxyConfigScheme(string proxyAddress, string url, out string proxyUrl)
  134. {
  135. proxyUrl = null;
  136. #if !WEBSOCKET_PROXYCONFIG
  137. if (!string.IsNullOrEmpty(proxyAddress))
  138. {
  139. if (proxyAddress.StartsWith("auto:") || proxyAddress.StartsWith("pac:") || proxyAddress.StartsWith("system:"))
  140. {
  141. this.Listener.DebugReturn(DebugLevel.WARNING, "Proxy configuration via auto, pac or system is only supported with the WEBSOCKET_PROXYCONFIG define. Using no proxy instead.");
  142. return true;
  143. }
  144. proxyUrl = proxyAddress;
  145. }
  146. return true;
  147. #else
  148. if (!string.IsNullOrEmpty(proxyAddress))
  149. {
  150. var httpUrl = url.ToString().Replace("ws://", "http://").Replace("wss://", "https://"); // http(s) schema required in GetProxyForUrlUsingPac call
  151. bool auto = proxyAddress.StartsWith("auto:", StringComparison.InvariantCultureIgnoreCase);
  152. bool pac = proxyAddress.StartsWith("pac:", StringComparison.InvariantCultureIgnoreCase);
  153. if (auto || pac)
  154. {
  155. string pacUrl = "";
  156. if (pac)
  157. {
  158. pacUrl = proxyAddress.Substring(4);
  159. if (pacUrl.IndexOf("://") == -1)
  160. {
  161. pacUrl = "http://" + pacUrl; //default to http
  162. }
  163. }
  164. string processTypeStr = auto ? "auto detect" : "pac url " + pacUrl;
  165. this.Listener.DebugReturn(DebugLevel.INFO, "WebSocket Proxy: " + url + " " + processTypeStr);
  166. string errDescr = "";
  167. var err = ProxyAutoConfig.GetProxyForUrlUsingPac(httpUrl, pacUrl, out proxyUrl, out errDescr);
  168. if (err != 0)
  169. {
  170. this.Listener.DebugReturn(DebugLevel.ERROR, "WebSocket Proxy: " + url + " " + processTypeStr + " ProxyAutoConfig.GetProxyForUrlUsingPac() error: " + err + " (" + errDescr + ")");
  171. return false;
  172. }
  173. }
  174. else if (proxyAddress.StartsWith("system:", StringComparison.InvariantCultureIgnoreCase))
  175. {
  176. this.Listener.DebugReturn(DebugLevel.INFO, "WebSocket Proxy: " + url + " system settings");
  177. string proxyAutoConfigPacUrl;
  178. var err = ProxySystemSettings.GetProxy(out proxyUrl, out proxyAutoConfigPacUrl);
  179. if (err != 0)
  180. {
  181. this.Listener.DebugReturn(DebugLevel.ERROR, "WebSocket Proxy: " + url + " system settings ProxySystemSettings.GetProxy() error: " + err);
  182. return false;
  183. }
  184. if (proxyAutoConfigPacUrl != null)
  185. {
  186. if (proxyAutoConfigPacUrl.IndexOf("://") == -1)
  187. {
  188. proxyAutoConfigPacUrl = "http://" + proxyAutoConfigPacUrl; //default to http
  189. }
  190. this.Listener.DebugReturn(DebugLevel.INFO, "WebSocket Proxy: " + url + " system settings AutoConfigURL: " + proxyAutoConfigPacUrl);
  191. string errDescr = "";
  192. err = ProxyAutoConfig.GetProxyForUrlUsingPac(httpUrl, proxyAutoConfigPacUrl, out proxyUrl, out errDescr);
  193. if (err != 0)
  194. {
  195. this.Listener.DebugReturn(DebugLevel.ERROR, "WebSocket Proxy: " + url + " system settings AutoConfigURLerror: " + err + " (" + errDescr + ")");
  196. return false;
  197. }
  198. }
  199. }
  200. else
  201. {
  202. proxyUrl = proxyAddress;
  203. }
  204. this.Listener.DebugReturn(DebugLevel.INFO, "WebSocket Proxy: " + url + " -> " + (string.IsNullOrEmpty(proxyUrl) ? "DIRECT" : "PROXY " + proxyUrl));
  205. }
  206. return true;
  207. #endif
  208. }
  209. public override bool Disconnect()
  210. {
  211. if (this.ReportDebugOfLevel(DebugLevel.INFO))
  212. {
  213. this.Listener.DebugReturn(DebugLevel.INFO, "SocketWebTcp.Disconnect()");
  214. }
  215. this.State = PhotonSocketState.Disconnecting;
  216. lock (this.syncer)
  217. {
  218. if (this.sock != null)
  219. {
  220. try
  221. {
  222. this.sock.Close();
  223. }
  224. catch (Exception ex)
  225. {
  226. this.Listener.DebugReturn(DebugLevel.ERROR, "Exception in SocketWebTcp.Disconnect(): " + ex);
  227. }
  228. this.sock = null;
  229. }
  230. }
  231. if (this.websocketConnectionObject != null)
  232. {
  233. UnityEngine.Object.Destroy(this.websocketConnectionObject);
  234. }
  235. this.State = PhotonSocketState.Disconnected;
  236. return true;
  237. }
  238. /// <summary>
  239. /// used by TPeer*
  240. /// </summary>
  241. public override PhotonSocketError Send(byte[] data, int length)
  242. {
  243. if (this.State != PhotonSocketState.Connected)
  244. {
  245. return PhotonSocketError.Skipped;
  246. }
  247. try
  248. {
  249. if (data.Length > length)
  250. {
  251. byte[] trimmedData = new byte[length];
  252. Buffer.BlockCopy(data, 0, trimmedData, 0, length);
  253. data = trimmedData;
  254. }
  255. //if (this.ReportDebugOfLevel(DebugLevel.ALL))
  256. //{
  257. // this.Listener.DebugReturn(DebugLevel.ALL, "Sending: " + SupportClassPun.ByteArrayToString(data));
  258. //}
  259. if (this.sock != null)
  260. {
  261. this.sock.Send(data);
  262. }
  263. }
  264. catch (Exception e)
  265. {
  266. this.Listener.DebugReturn(DebugLevel.ERROR, "Cannot send to: " + this.ServerAddress + ". " + e.Message);
  267. this.HandleException(StatusCode.Exception);
  268. return PhotonSocketError.Exception;
  269. }
  270. return PhotonSocketError.Success;
  271. }
  272. public override PhotonSocketError Receive(out byte[] data)
  273. {
  274. data = null;
  275. return PhotonSocketError.NoData;
  276. }
  277. internal const int ALL_HEADER_BYTES = 9;
  278. internal const int TCP_HEADER_BYTES = 7;
  279. internal const int MSG_HEADER_BYTES = 2;
  280. public IEnumerator ReceiveLoop()
  281. {
  282. //this.Listener.DebugReturn(DebugLevel.INFO, "ReceiveLoop()");
  283. if (this.sock != null)
  284. {
  285. while (this.sock != null && !this.sock.Connected && this.sock.Error == null)
  286. {
  287. yield return new WaitForRealSeconds(0.1f);
  288. }
  289. if (this.sock != null)
  290. {
  291. if (this.sock.Error != null)
  292. {
  293. this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread. Server: " + this.ServerAddress + " Error: " + this.sock.Error);
  294. this.HandleException(StatusCode.ExceptionOnConnect);
  295. }
  296. else
  297. {
  298. // connected
  299. if (this.ReportDebugOfLevel(DebugLevel.ALL))
  300. {
  301. this.Listener.DebugReturn(DebugLevel.ALL, "Receiving by websocket. this.State: " + this.State);
  302. }
  303. this.State = PhotonSocketState.Connected;
  304. this.peerBase.OnConnect();
  305. while (this.State == PhotonSocketState.Connected)
  306. {
  307. if (this.sock != null)
  308. {
  309. if (this.sock.Error != null)
  310. {
  311. this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread (inside loop). Server: " + this.ServerAddress + " Error: " + this.sock.Error);
  312. this.HandleException(StatusCode.ExceptionOnReceive);
  313. break;
  314. }
  315. else
  316. {
  317. byte[] inBuff = this.sock.Recv();
  318. if (inBuff == null || inBuff.Length == 0)
  319. {
  320. // nothing received. wait a bit, try again
  321. yield return new WaitForRealSeconds(0.02f);
  322. continue;
  323. }
  324. //if (this.ReportDebugOfLevel(DebugLevel.ALL))
  325. //{
  326. // this.Listener.DebugReturn(DebugLevel.ALL, "TCP << " + inBuff.Length + " = " + SupportClassPun.ByteArrayToString(inBuff));
  327. //}
  328. if (inBuff.Length > 0)
  329. {
  330. try
  331. {
  332. this.HandleReceivedDatagram(inBuff, inBuff.Length, false);
  333. }
  334. catch (Exception e)
  335. {
  336. if (this.State != PhotonSocketState.Disconnecting && this.State != PhotonSocketState.Disconnected)
  337. {
  338. if (this.ReportDebugOfLevel(DebugLevel.ERROR))
  339. {
  340. this.EnqueueDebugReturn(DebugLevel.ERROR, "Receive issue. State: " + this.State + ". Server: '" + this.ServerAddress + "' Exception: " + e);
  341. }
  342. this.HandleException(StatusCode.ExceptionOnReceive);
  343. }
  344. }
  345. }
  346. }
  347. }
  348. }
  349. }
  350. }
  351. }
  352. this.Disconnect();
  353. }
  354. private class MonoBehaviourExt : MonoBehaviour
  355. {
  356. }
  357. }
  358. }
  359. #endif