AsyncTestHubSample.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  2. using System;
  3. using UnityEngine;
  4. using BestHTTP.SignalRCore;
  5. using BestHTTP.SignalRCore.Encoders;
  6. using UnityEngine.UI;
  7. using BestHTTP.Examples.Helpers;
  8. #if CSHARP_7_OR_LATER
  9. using System.Threading.Tasks;
  10. #endif
  11. namespace BestHTTP.Examples
  12. {
  13. // Server side of this example can be found here:
  14. // https://github.com/Benedicht/BestHTTP_DemoSite/blob/master/BestHTTP_DemoSite/Hubs/TestHub.cs
  15. public class AsyncTestHubSample : BestHTTP.Examples.Helpers.SampleBase
  16. {
  17. #pragma warning disable 0649
  18. #pragma warning disable 0414
  19. [SerializeField]
  20. private string _path = "/TestHub";
  21. [SerializeField]
  22. private ScrollRect _scrollRect;
  23. [SerializeField]
  24. private RectTransform _contentRoot;
  25. [SerializeField]
  26. private TextListItem _listItemPrefab;
  27. [SerializeField]
  28. private int _maxListItemEntries = 100;
  29. [SerializeField]
  30. private Button _connectButton;
  31. [SerializeField]
  32. private Button _closeButton;
  33. #pragma warning restore
  34. // Instance of the HubConnection
  35. HubConnection hub;
  36. protected override void Start()
  37. {
  38. base.Start();
  39. #if !CSHARP_7_OR_LATER
  40. AddText("<color=red>This sample can work only when at least c# 7.3 is supported!</color>");
  41. SetButtons(false, false);
  42. #else
  43. SetButtons(true, false);
  44. #endif
  45. }
  46. #if CSHARP_7_OR_LATER
  47. async void OnDestroy()
  48. {
  49. await hub?.CloseAsync();
  50. }
  51. #endif
  52. /// <summary>
  53. /// GUI button callback
  54. /// </summary>
  55. public
  56. #if CSHARP_7_OR_LATER
  57. async
  58. #endif
  59. void OnConnectButton()
  60. {
  61. #if CSHARP_7_OR_LATER
  62. #if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
  63. try
  64. {
  65. MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
  66. MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
  67. MessagePack.Unity.UnityResolver.Instance,
  68. //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
  69. //MessagePack.Resolvers.StandardResolver.Instance,
  70. MessagePack.Resolvers.ContractlessStandardResolver.Instance
  71. );
  72. var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
  73. MessagePack.MessagePackSerializer.DefaultOptions = options;
  74. }
  75. catch
  76. { }
  77. #endif
  78. IProtocol protocol = null;
  79. #if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
  80. protocol = new MessagePackCSharpProtocol();
  81. #elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
  82. protocol = new MessagePackProtocol();
  83. #else
  84. protocol = new JsonProtocol(new LitJsonEncoder());
  85. #endif
  86. // Crete the HubConnection
  87. hub = new HubConnection(new Uri(this.sampleSelector.BaseURL + this._path), protocol);
  88. // Subscribe to hub events
  89. hub.OnError += Hub_OnError;
  90. hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));
  91. // Set up server callable functions
  92. hub.On("Send", (string arg) => AddText(string.Format("On '<color=green>Send</color>': '<color=yellow>{0}</color>'", arg)).AddLeftPadding(20));
  93. hub.On<Person>("Person", (person) => AddText(string.Format("On '<color=green>Person</color>': '<color=yellow>{0}</color>'", person)).AddLeftPadding(20));
  94. hub.On<Person, Person>("TwoPersons", (person1, person2) => AddText(string.Format("On '<color=green>TwoPersons</color>': '<color=yellow>{0}</color>', '<color=yellow>{1}</color>'", person1, person2)).AddLeftPadding(20));
  95. AddText("StartConnect called");
  96. SetButtons(false, false);
  97. // And finally start to connect to the server
  98. await hub.ConnectAsync();
  99. SetButtons(false, true);
  100. AddText(string.Format("Hub Connected with <color=green>{0}</color> transport using the <color=green>{1}</color> encoder.", hub.Transport.TransportType.ToString(), hub.Protocol.Name));
  101. // Call a server function with a string param. We expect no return value.
  102. await hub.SendAsync("Send", "my message");
  103. // Call a parameterless function. We expect a string return value.
  104. try
  105. {
  106. string result = await hub.InvokeAsync<string>("NoParam");
  107. AddText(string.Format("'<color=green>NoParam</color>' returned: '<color=yellow>{0}</color>'", result))
  108. .AddLeftPadding(20);
  109. }
  110. catch (Exception ex)
  111. {
  112. AddText(string.Format("'<color=green>NoParam</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
  113. }
  114. // Call a function on the server to add two numbers. OnSuccess will be called with the result and OnError if there's an error.
  115. var addResult = await hub.InvokeAsync<int>("Add", 10, 20);
  116. AddText(string.Format("'<color=green>Add(10, 20)</color>' returned: '<color=yellow>{0}</color>'", addResult)).AddLeftPadding(20);
  117. var nullabelTestResult = await hub.InvokeAsync<int?>("NullableTest", 10);
  118. AddText(string.Format("'<color=green>NullableTest(10)</color>' returned: '<color=yellow>{0}</color>'", nullabelTestResult)).AddLeftPadding(20);
  119. // Call a function that will return a Person object constructed from the function's parameters.
  120. var getPersonResult = await hub.InvokeAsync<Person>("GetPerson", "Mr. Smith", 26);
  121. AddText(string.Format("'<color=green>GetPerson(\"Mr. Smith\", 26)</color>' returned: '<color=yellow>{0}</color>'", getPersonResult)).AddLeftPadding(20);
  122. // To test errors/exceptions this call always throws an exception on the server side resulting in an OnError call.
  123. // OnError expected here!
  124. try
  125. {
  126. var singleResultFailureResult = await hub.InvokeAsync<int>("SingleResultFailure", 10, 20);
  127. AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' returned: '<color=yellow>{0}</color>'", singleResultFailureResult)).AddLeftPadding(20);
  128. }
  129. catch (Exception ex)
  130. {
  131. AddText(string.Format("'<color=green>SingleResultFailure(10, 20)</color>' error: '<color=red>{0}</color>'", ex.Message)).AddLeftPadding(20);
  132. }
  133. // This call demonstrates IEnumerable<> functions, result will be the yielded numbers.
  134. var batchedResult = await hub.InvokeAsync<int[]>("Batched", 10);
  135. AddText(string.Format("'<color=green>Batched(10)</color>' returned items: '<color=yellow>{0}</color>'", batchedResult.Length)).AddLeftPadding(20);
  136. // OnItem is called for a streaming request for every items returned by the server. OnSuccess will still be called with all the items.
  137. hub.GetDownStreamController<int>("ObservableCounter", 10, 1000)
  138. .OnItem(result => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
  139. .OnSuccess(result => AddText("'<color=green>ObservableCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
  140. .OnError(error => AddText(string.Format("'<color=green>ObservableCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));
  141. // A stream request can be cancelled any time.
  142. var controller = hub.GetDownStreamController<int>("ChannelCounter", 10, 1000);
  143. controller.OnItem(result => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
  144. .OnSuccess(result => AddText("'<color=green>ChannelCounter(10, 1000)</color>' OnSuccess.").AddLeftPadding(20))
  145. .OnError(error => AddText(string.Format("'<color=green>ChannelCounter(10, 1000)</color>' error: '<color=red>{0}</color>'", error)).AddLeftPadding(20));
  146. // a stream can be cancelled by calling the controller's Cancel method
  147. controller.Cancel();
  148. // This call will stream strongly typed objects
  149. hub.GetDownStreamController<Person>("GetRandomPersons", 20, 2000)
  150. .OnItem(result => AddText(string.Format("'<color=green>GetRandomPersons(20, 1000)</color>' OnItem: '<color=yellow>{0}</color>'", result)).AddLeftPadding(20))
  151. .OnSuccess(result => AddText("'<color=green>GetRandomPersons(20, 1000)</color>' OnSuccess.").AddLeftPadding(20));
  152. #endif
  153. }
  154. /// <summary>
  155. /// GUI button callback
  156. /// </summary>
  157. public
  158. #if CSHARP_7_OR_LATER
  159. async
  160. #endif
  161. void OnCloseButton()
  162. {
  163. #if CSHARP_7_OR_LATER
  164. if (this.hub != null)
  165. {
  166. AddText("Calling CloseAsync");
  167. SetButtons(false, false);
  168. await this.hub.CloseAsync();
  169. SetButtons(true, false);
  170. AddText("Hub Closed");
  171. }
  172. #endif
  173. }
  174. /// <summary>
  175. /// Called when an unrecoverable error happen. After this event the hub will not send or receive any messages.
  176. /// </summary>
  177. private void Hub_OnError(HubConnection hub, string error)
  178. {
  179. SetButtons(true, false);
  180. AddText(string.Format("Hub Error: <color=red>{0}</color>", error));
  181. }
  182. private void SetButtons(bool connect, bool close)
  183. {
  184. if (this._connectButton != null)
  185. this._connectButton.interactable = connect;
  186. if (this._closeButton != null)
  187. this._closeButton.interactable = close;
  188. }
  189. private TextListItem AddText(string text)
  190. {
  191. return GUIHelper.AddText(this._listItemPrefab, this._contentRoot, text, this._maxListItemEntries, this._scrollRect);
  192. }
  193. }
  194. }
  195. #endif