SampleSelector.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using BestHTTP;
  5. using BestHTTP.Statistics;
  6. using BestHTTP.Examples;
  7. namespace BestHTTP.Examples
  8. {
  9. /// <summary>
  10. /// A class to describe an Example and store it's metadata.
  11. /// </summary>
  12. public sealed class SampleDescriptor
  13. {
  14. public bool IsLabel { get; set; }
  15. public Type Type { get; set; }
  16. public string DisplayName { get; set; }
  17. public string Description { get; set; }
  18. public bool IsSelected { get; set; }
  19. public GameObject UnityObject { get; set; }
  20. public bool IsRunning { get { return UnityObject != null; } }
  21. public SampleDescriptor(Type type, string displayName, string description)
  22. {
  23. this.Type = type;
  24. this.DisplayName = displayName;
  25. this.Description = description;
  26. }
  27. public void CreateUnityObject()
  28. {
  29. if (UnityObject != null)
  30. return;
  31. UnityObject = new GameObject(DisplayName);
  32. UnityObject.AddComponent(Type);
  33. }
  34. public void DestroyUnityObject()
  35. {
  36. if (UnityObject != null)
  37. {
  38. UnityEngine.Object.Destroy(UnityObject);
  39. UnityObject = null;
  40. }
  41. }
  42. }
  43. public class SampleSelector : MonoBehaviour
  44. {
  45. public const int statisticsHeight = 160;
  46. List<SampleDescriptor> Samples = new List<SampleDescriptor>();
  47. public static SampleDescriptor SelectedSample;
  48. Vector2 scrollPos;
  49. void Awake()
  50. {
  51. Application.runInBackground = true;
  52. HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
  53. #if UNITY_SAMSUNGTV
  54. SamsungTV.touchPadMode = SamsungTV.TouchPadMode.Mouse;
  55. // Create a red 'cursor' to see where we are pointing to
  56. Texture2D tex = new Texture2D(8, 8, TextureFormat.RGB24, false);
  57. for (int i = 0; i < tex.width; ++i)
  58. for (int cv = 0; cv < tex.height; ++cv)
  59. tex.SetPixel(i, cv, Color.red);
  60. tex.Apply(false, true);
  61. Cursor.SetCursor(tex, Vector2.zero, CursorMode.Auto);
  62. #endif
  63. Samples.Add(new SampleDescriptor(null, "HTTP Samples", string.Empty) { IsLabel = true });
  64. Samples.Add(new SampleDescriptor(typeof(TextureDownloadSample), "Texture Download", "With HTTPManager.MaxConnectionPerServer you can control how many requests can be processed per server parallel.\n\nFeatures demoed in this example:\n-Parallel requests to the same server\n-Controlling the parallelization\n-Automatic Caching\n-Create a Texture2D from the downloaded data"));
  65. Samples.Add(new SampleDescriptor(typeof(AssetBundleSample), "AssetBundle Download", "A small example that shows a possible way to download an AssetBundle and load a resource from it.\n\nFeatures demoed in this example:\n-Using HTTPRequest without a callback\n-Using HTTPRequest in a Coroutine\n-Loading an AssetBundle from the downloaded bytes\n-Automatic Caching"));
  66. #if !UNITY_WEBGL || UNITY_EDITOR
  67. Samples.Add(new SampleDescriptor(typeof(LargeFileDownloadSample), "Large File Download", "This example demonstrates how you can download a (large) file and continue the download after the connection is aborted.\n\nFeatures demoed in this example:\n-Setting up a streamed download\n-How to access the downloaded data while the download is in progress\n-Setting the HTTPRequest's StreamFragmentSize to controll the frequency and size of the fragments\n-How to use the SetRangeHeader to continue a previously disconnected download\n-How to disable the local, automatic caching"));
  68. #endif
  69. #if !BESTHTTP_DISABLE_WEBSOCKET
  70. Samples.Add(new SampleDescriptor(null, "WebSocket Samples", string.Empty) { IsLabel = true });
  71. Samples.Add(new SampleDescriptor(typeof(WebSocketSample), "Echo", "A WebSocket demonstration that connects to a WebSocket echo service.\n\nFeatures demoed in this example:\n-Basic usage of the WebSocket class"));
  72. #endif
  73. #if !BESTHTTP_DISABLE_SOCKETIO
  74. Samples.Add(new SampleDescriptor(null, "Socket.IO Samples", string.Empty) { IsLabel = true });
  75. Samples.Add(new SampleDescriptor(typeof(SocketIOChatSample), "Chat", "This example uses the Socket.IO implementation to connect to the official Chat demo server(http://chat.socket.io/).\n\nFeatures demoed in this example:\n-Instantiating and setting up a SocketManager to connect to a Socket.IO server\n-Changing SocketOptions property\n-Subscribing to Socket.IO events\n-Sending custom events to the server"));
  76. #if !UNITY_WEBGL || UNITY_EDITOR
  77. Samples.Add(new SampleDescriptor(typeof(SocketIOWePlaySample), "WePlay", "This example uses the Socket.IO implementation to connect to the official WePlay demo server(http://weplay.io/).\n\nFeatures demoed in this example:\n-Instantiating and setting up a SocketManager to connect to a Socket.IO server\n-Subscribing to Socket.IO events\n-Receiving binary data\n-How to load a texture from the received binary data\n-How to disable payload decoding for fine tune for some speed\n-Sending custom events to the server"));
  78. #endif
  79. #endif
  80. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  81. Samples.Add(new SampleDescriptor(null, "SignalR Core Samples", string.Empty) { IsLabel = true });
  82. Samples.Add(new SampleDescriptor(typeof(TestHubExample), "Hub Sample", "This sample demonstrates most of the functionalities of the SignalR protocol:\n-How to set up HubConnection to connect to the server\n-Subscribing to server-callable function\n-Calling client-callable function on the server\n-Calling and handling streaming\n"));
  83. Samples.Add(new SampleDescriptor(typeof(HubWithAuthorizationSample), "Hub Authentication Sample", "This sample demonstrates the default access token authentication. The server sends a JWT token to the client with a new url. The client will connect to that new url and sends the JWT token.\n"));
  84. Samples.Add(new SampleDescriptor(typeof(HubWithPreAuthorizationSample), "Hub Pre-Authentication Sample", "This sample demonstrates manual authentication.\n"));
  85. Samples.Add(new SampleDescriptor(typeof(RedirectSample), "Hub Redirect Sample", "This sample demonstrates how the plugin handles redirection through the SignalR Core negotiation data.\n"));
  86. #endif
  87. #if (!BESTHTTP_DISABLE_SIGNALR && !UNITY_WEBGL) || UNITY_EDITOR
  88. Samples.Add(new SampleDescriptor(null, "SignalR Samples", string.Empty) { IsLabel = true });
  89. Samples.Add(new SampleDescriptor(typeof(SimpleStreamingSample), "Simple Streaming", "A very simple example of a background thread that broadcasts the server time to all connected clients every two seconds.\n\nFeatures demoed in this example:\n-Subscribing and handling non-hub messages"));
  90. Samples.Add(new SampleDescriptor(typeof(ConnectionAPISample), "Connection API", "Demonstrates all features of the lower-level connection API including starting and stopping, sending and receiving messages, and managing groups.\n\nFeatures demoed in this example:\n-Instantiating and setting up a SignalR Connection to connect to a SignalR server\n-Changing the default Json encoder\n-Subscribing to state changes\n-Receiving and handling of non-hub messages\n-Sending non-hub messages\n-Managing groups"));
  91. Samples.Add(new SampleDescriptor(typeof(ConnectionStatusSample), "Connection Status", "Demonstrates how to handle the events that are raised when connections connect, reconnect and disconnect from the Hub API.\n\nFeatures demoed in this example:\n-Connecting to a Hub\n-Setting up a callback for Hub events\n-Handling server-sent method call requests\n-Calling a Hub-method on the server-side\n-Opening and closing the SignalR Connection"));
  92. Samples.Add(new SampleDescriptor(typeof(DemoHubSample), "Demo Hub", "A contrived example that exploits every feature of the Hub API.\n\nFeatures demoed in this example:\n-Creating and using wrapper Hub classes to encapsulate hub functions and events\n-Handling long running server-side functions by handling progress messages\n-Groups\n-Handling server-side functions with return value\n-Handling server-side functions throwing Exceptions\n-Calling server-side functions with complex type parameters\n-Calling server-side functions with array parameters\n-Calling overloaded server-side functions\n-Changing Hub states\n-Receiving and handling hub state changes\n-Calling server-side functions implemented in VB .NET"));
  93. #if !UNITY_WEBGL || UNITY_EDITOR
  94. Samples.Add(new SampleDescriptor(typeof(AuthenticationSample), "Authentication", "Demonstrates how to use the authorization features of the Hub API to restrict certain Hubs and methods to specific users.\n\nFeatures demoed in this example:\n-Creating and using wrapper Hub classes to encapsulate hub functions and events\n-Create and use a Header-based authenticator to access protected APIs\n-SignalR over HTTPS"));
  95. #endif
  96. #endif
  97. #if !BESTHTTP_DISABLE_CACHING
  98. Samples.Add(new SampleDescriptor(null, "Plugin Samples", string.Empty) { IsLabel = true });
  99. Samples.Add(new SampleDescriptor(typeof(CacheMaintenanceSample), "Cache Maintenance", "With this demo you can see how you can use the HTTPCacheService's BeginMaintainence function to delete too old cached entities and keep the cache size under a specified value.\n\nFeatures demoed in this example:\n-How to set up a HTTPCacheMaintananceParams\n-How to call the BeginMaintainence function"));
  100. #endif
  101. SelectedSample = Samples[1];
  102. }
  103. void Update()
  104. {
  105. GUIHelper.ClientArea = new Rect(0, SampleSelector.statisticsHeight + 5, Screen.width, Screen.height - SampleSelector.statisticsHeight - 50);
  106. if (Input.GetKeyDown(KeyCode.Escape))
  107. {
  108. if (SelectedSample != null && SelectedSample.IsRunning)
  109. SelectedSample.DestroyUnityObject();
  110. else
  111. Application.Quit();
  112. }
  113. if (Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return))
  114. {
  115. if (SelectedSample != null && !SelectedSample.IsRunning)
  116. SelectedSample.CreateUnityObject();
  117. }
  118. }
  119. void OnGUI()
  120. {
  121. var stats = HTTPManager.GetGeneralStatistics(StatisticsQueryFlags.All);
  122. // Connection statistics
  123. GUIHelper.DrawArea(new Rect(0, 0, Screen.width / 3, statisticsHeight), false, () =>
  124. {
  125. // Header
  126. GUIHelper.DrawCenteredText("Connections");
  127. GUILayout.Space(5);
  128. GUIHelper.DrawRow("Sum:", stats.Connections.ToString());
  129. GUIHelper.DrawRow("Active:", stats.ActiveConnections.ToString());
  130. GUIHelper.DrawRow("Free:", stats.FreeConnections.ToString());
  131. GUIHelper.DrawRow("Recycled:", stats.RecycledConnections.ToString());
  132. GUIHelper.DrawRow("Requests in queue:", stats.RequestsInQueue.ToString());
  133. });
  134. // Cache statistics
  135. GUIHelper.DrawArea(new Rect(Screen.width / 3, 0, Screen.width / 3, statisticsHeight), false, () =>
  136. {
  137. GUIHelper.DrawCenteredText("Cache");
  138. #if !BESTHTTP_DISABLE_CACHING
  139. if (!BestHTTP.Caching.HTTPCacheService.IsSupported)
  140. {
  141. #endif
  142. GUI.color = Color.yellow;
  143. GUIHelper.DrawCenteredText("Disabled in WebPlayer, WebGL & Samsung Smart TV Builds!");
  144. GUI.color = Color.white;
  145. #if !BESTHTTP_DISABLE_CACHING
  146. }
  147. else
  148. {
  149. GUILayout.Space(5);
  150. GUIHelper.DrawRow("Cached entities:", stats.CacheEntityCount.ToString());
  151. GUIHelper.DrawRow("Sum Size (bytes): ", stats.CacheSize.ToString("N0"));
  152. GUILayout.BeginVertical();
  153. GUILayout.FlexibleSpace();
  154. if (GUILayout.Button("Clear Cache"))
  155. BestHTTP.Caching.HTTPCacheService.BeginClear();
  156. GUILayout.EndVertical();
  157. }
  158. #endif
  159. });
  160. // Cookie statistics
  161. GUIHelper.DrawArea(new Rect((Screen.width / 3) * 2, 0, Screen.width / 3, statisticsHeight), false, () =>
  162. {
  163. GUIHelper.DrawCenteredText("Cookies");
  164. #if !BESTHTTP_DISABLE_COOKIES
  165. if (!BestHTTP.Cookies.CookieJar.IsSavingSupported)
  166. {
  167. #endif
  168. GUI.color = Color.yellow;
  169. GUIHelper.DrawCenteredText("Saving and loading from disk is disabled in WebPlayer, WebGL & Samsung Smart TV Builds!");
  170. GUI.color = Color.white;
  171. #if !BESTHTTP_DISABLE_COOKIES
  172. }
  173. else
  174. {
  175. GUILayout.Space(5);
  176. GUIHelper.DrawRow("Cookies:", stats.CookieCount.ToString());
  177. GUIHelper.DrawRow("Estimated size (bytes):", stats.CookieJarSize.ToString("N0"));
  178. GUILayout.BeginVertical();
  179. GUILayout.FlexibleSpace();
  180. if (GUILayout.Button("Clear Cookies"))
  181. BestHTTP.Cookies.CookieJar.Clear();
  182. GUILayout.EndVertical();
  183. }
  184. #endif
  185. });
  186. if (SelectedSample == null || (SelectedSample != null && !SelectedSample.IsRunning))
  187. {
  188. // Draw the list of samples
  189. GUIHelper.DrawArea(new Rect(0, statisticsHeight + 5, SelectedSample == null ? Screen.width : Screen.width / 3, Screen.height - statisticsHeight - 5), false, () =>
  190. {
  191. scrollPos = GUILayout.BeginScrollView(scrollPos);
  192. for (int i = 0; i < Samples.Count; ++i)
  193. DrawSample(Samples[i]);
  194. GUILayout.EndScrollView();
  195. });
  196. if (SelectedSample != null)
  197. DrawSampleDetails(SelectedSample);
  198. }
  199. else if (SelectedSample != null && SelectedSample.IsRunning)
  200. {
  201. GUILayout.BeginArea(new Rect(0, Screen.height - 50, Screen.width, 50), string.Empty);
  202. GUILayout.FlexibleSpace();
  203. GUILayout.BeginHorizontal();
  204. GUILayout.FlexibleSpace();
  205. GUILayout.BeginVertical();
  206. GUILayout.FlexibleSpace();
  207. if (GUILayout.Button("Back", GUILayout.MinWidth(100)))
  208. SelectedSample.DestroyUnityObject();
  209. GUILayout.FlexibleSpace();
  210. GUILayout.EndVertical();
  211. GUILayout.EndHorizontal();
  212. GUILayout.EndArea();
  213. }
  214. }
  215. private void DrawSample(SampleDescriptor sample)
  216. {
  217. if (sample.IsLabel)
  218. {
  219. GUILayout.Space(15);
  220. GUIHelper.DrawCenteredText(sample.DisplayName);
  221. GUILayout.Space(5);
  222. }
  223. else if (GUILayout.Button(sample.DisplayName))
  224. {
  225. sample.IsSelected = true;
  226. if (SelectedSample != null)
  227. SelectedSample.IsSelected = false;
  228. SelectedSample = sample;
  229. }
  230. }
  231. private void DrawSampleDetails(SampleDescriptor sample)
  232. {
  233. Rect area = new Rect(Screen.width / 3, statisticsHeight + 5, (Screen.width / 3) * 2, Screen.height - statisticsHeight - 5);
  234. GUI.Box(area, string.Empty);
  235. GUILayout.BeginArea(area);
  236. GUILayout.BeginVertical();
  237. GUIHelper.DrawCenteredText(sample.DisplayName);
  238. GUILayout.Space(5);
  239. GUILayout.Label(sample.Description);
  240. GUILayout.FlexibleSpace();
  241. if (GUILayout.Button("Start Sample"))
  242. sample.CreateUnityObject();
  243. GUILayout.EndVertical();
  244. GUILayout.EndArea();
  245. }
  246. }
  247. }