HubWithAuthorizationSample.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  2. using BestHTTP.Examples;
  3. using BestHTTP.Examples.Helpers;
  4. using BestHTTP.SignalRCore;
  5. using BestHTTP.SignalRCore.Encoders;
  6. using System;
  7. using UnityEngine;
  8. using UnityEngine.UI;
  9. namespace BestHTTP.Examples
  10. {
  11. /// <summary>
  12. /// A sample to demonstrate Bearer token authorization on the server. The client will connect to the /redirect route
  13. /// where it will receive the token and will receive the new url (/HubWithAuthorization) to connect to.
  14. /// HubWithAuthorization without the token would throw an error.
  15. /// </summary>
  16. public sealed class HubWithAuthorizationSample : BestHTTP.Examples.Helpers.SampleBase
  17. {
  18. #pragma warning disable 0649
  19. [SerializeField]
  20. private string _path = "/redirect";
  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. SetButtons(true, false);
  40. }
  41. void OnDestroy()
  42. {
  43. if (hub != null)
  44. hub.StartClose();
  45. }
  46. public void OnConnectButton()
  47. {
  48. // Server side of this example can be found here:
  49. // https://github.com/Benedicht/BestHTTP_DemoSite/blob/master/BestHTTP_DemoSite/Hubs/
  50. #if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
  51. try
  52. {
  53. MessagePack.Resolvers.StaticCompositeResolver.Instance.Register(
  54. MessagePack.Resolvers.DynamicEnumAsStringResolver.Instance,
  55. MessagePack.Unity.UnityResolver.Instance,
  56. //MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
  57. //MessagePack.Resolvers.StandardResolver.Instance,
  58. MessagePack.Resolvers.ContractlessStandardResolver.Instance
  59. );
  60. var options = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(MessagePack.Resolvers.StaticCompositeResolver.Instance);
  61. MessagePack.MessagePackSerializer.DefaultOptions = options;
  62. }
  63. catch
  64. { }
  65. #endif
  66. IProtocol protocol = null;
  67. #if BESTHTTP_SIGNALR_CORE_ENABLE_MESSAGEPACK_CSHARP
  68. protocol = new MessagePackCSharpProtocol();
  69. #elif BESTHTTP_SIGNALR_CORE_ENABLE_GAMEDEVWARE_MESSAGEPACK
  70. protocol = new MessagePackProtocol();
  71. #else
  72. protocol = new JsonProtocol(new LitJsonEncoder());
  73. #endif
  74. // Crete the HubConnection
  75. hub = new HubConnection(new Uri(base.sampleSelector.BaseURL + this._path), protocol);
  76. // Subscribe to hub events
  77. hub.OnConnected += Hub_OnConnected;
  78. hub.OnError += Hub_OnError;
  79. hub.OnClosed += Hub_OnClosed;
  80. hub.OnRedirected += Hub_Redirected;
  81. hub.OnTransportEvent += (hub, transport, ev) => AddText(string.Format("Transport(<color=green>{0}</color>) event: <color=green>{1}</color>", transport.TransportType, ev));
  82. // And finally start to connect to the server
  83. hub.StartConnect();
  84. AddText("StartConnect called");
  85. SetButtons(false, false);
  86. }
  87. public void OnCloseButton()
  88. {
  89. if (hub != null)
  90. {
  91. hub.StartClose();
  92. AddText("StartClose called");
  93. SetButtons(false, false);
  94. }
  95. }
  96. private void Hub_Redirected(HubConnection hub, Uri oldUri, Uri newUri)
  97. {
  98. AddText(string.Format("Hub connection redirected to '<color=green>{0}</color>' with Access Token: '<color=green>{1}</color>'", hub.Uri, hub.NegotiationResult.AccessToken));
  99. }
  100. /// <summary>
  101. /// This callback is called when the plugin is connected to the server successfully. Messages can be sent to the server after this point.
  102. /// </summary>
  103. private void Hub_OnConnected(HubConnection hub)
  104. {
  105. 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));
  106. SetButtons(false, true);
  107. // Call a parameterless function. We expect a string return value.
  108. hub.Invoke<string>("Echo", "Message from the client")
  109. .OnSuccess(ret => AddText(string.Format("'<color=green>Echo</color>' returned: '<color=yellow>{0}</color>'", ret)).AddLeftPadding(20));
  110. AddText("'<color=green>Message from the client</color>' sent!")
  111. .AddLeftPadding(20);
  112. }
  113. /// <summary>
  114. /// This is called when the hub is closed after a StartClose() call.
  115. /// </summary>
  116. private void Hub_OnClosed(HubConnection hub)
  117. {
  118. AddText("Hub Closed");
  119. SetButtons(true, false);
  120. }
  121. /// <summary>
  122. /// Called when an unrecoverable error happen. After this event the hub will not send or receive any messages.
  123. /// </summary>
  124. private void Hub_OnError(HubConnection hub, string error)
  125. {
  126. AddText(string.Format("Hub Error: <color=red>{0}</color>", error));
  127. SetButtons(true, false);
  128. }
  129. private void SetButtons(bool connect, bool close)
  130. {
  131. if (this._connectButton != null)
  132. this._connectButton.interactable = connect;
  133. if (this._closeButton != null)
  134. this._closeButton.interactable = close;
  135. }
  136. private TextListItem AddText(string text)
  137. {
  138. return GUIHelper.AddText(this._listItemPrefab, this._contentRoot, text, this._maxListItemEntries, this._scrollRect);
  139. }
  140. }
  141. }
  142. #endif