TestHubSample.cs 11 KB

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