TestHubExample.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  2. using System;
  3. using UnityEngine;
  4. using BestHTTP.SignalRCore;
  5. using BestHTTP.SignalRCore.Encoders;
  6. namespace BestHTTP.Examples
  7. {
  8. public class TestHubExample : MonoBehaviour
  9. {
  10. // Server uri to connect to
  11. readonly Uri URI = new Uri(GUIHelper.BaseURL + "/TestHub");
  12. // Instance of the HubConnection
  13. HubConnection hub;
  14. Vector2 scrollPos;
  15. string uiText;
  16. void Start()
  17. {
  18. // Server side of this example can be found here:
  19. // https://github.com/Benedicht/BestHTTP_DemoSite/blob/master/BestHTTP_DemoSite/Hubs/TestHub.cs
  20. // Set up optional options
  21. HubOptions options = new HubOptions();
  22. options.SkipNegotiation = false;
  23. // Crete the HubConnection
  24. hub = new HubConnection(URI, new JsonProtocol(new LitJsonEncoder()), options);
  25. // Optionally add an authenticator
  26. //hub.AuthenticationProvider = new BestHTTP.SignalRCore.Authentication.HeaderAuthenticator("<generated jwt token goes here>");
  27. // Subscribe to hub events
  28. hub.OnConnected += Hub_OnConnected;
  29. hub.OnError += Hub_OnError;
  30. hub.OnClosed += Hub_OnClosed;
  31. hub.OnMessage += Hub_OnMessage;
  32. // Set up server callable functions
  33. hub.On("Send", (string arg) => uiText += string.Format(" On Send: {0}\n", arg));
  34. hub.On<Person>("Person", (person) => uiText += string.Format(" On Person: {0}\n", person));
  35. hub.On<Person, Person>("TwoPersons", (person1, person2) => uiText += string.Format(" On TwoPersons: {0}, {1}\n", person1, person2));
  36. // And finally start to connect to the server
  37. hub.StartConnect();
  38. uiText = "StartConnect called\n";
  39. }
  40. void OnDestroy()
  41. {
  42. if (hub != null)
  43. hub.StartClose();
  44. }
  45. // Draw the text stored in the 'uiText' field
  46. void OnGUI()
  47. {
  48. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  49. {
  50. scrollPos = GUILayout.BeginScrollView(scrollPos, false, false);
  51. GUILayout.BeginVertical();
  52. GUILayout.Label(uiText);
  53. GUILayout.EndVertical();
  54. GUILayout.EndScrollView();
  55. });
  56. }
  57. /// <summary>
  58. /// This callback is called when the plugin is connected to the server successfully. Messages can be sent to the server after this point.
  59. /// </summary>
  60. private void Hub_OnConnected(HubConnection hub)
  61. {
  62. uiText += "Hub Connected\n";
  63. // Call a server function with a string param. We expect no return value.
  64. hub.Send("Send", "my message");
  65. // Call a parameterless function. We expect a string return value.
  66. hub.Invoke<string>("NoParam")
  67. .OnSuccess(ret => uiText += string.Format(" 'NoParam' returned: {0}\n", ret));
  68. // Call a function on the server to add two numbers. OnSuccess will be called with the result and OnError if there's an error.
  69. hub.Invoke<int>("Add", 10, 20)
  70. .OnSuccess(result => uiText += string.Format(" 'Add(10, 20)' returned: {0}\n", result))
  71. .OnError(error => uiText += string.Format(" 'Add(10, 20)' error: {0}\n", error));
  72. // Call a function that will return a Person object constructed from the function's parameters.
  73. hub.Invoke<Person>("GetPerson", "Mr. Smith", 26)
  74. .OnSuccess(result => uiText += string.Format(" 'GetPerson(\"Mr. Smith\", 26)' returned: {0}\n", result))
  75. .OnError(error => uiText += string.Format(" 'GetPerson(\"Mr. Smith\", 26)' error: {0}\n", error));
  76. // To test errors/exceptions this call always throws an exception on the server side resulting in an OnError call.
  77. // OnError expected here!
  78. hub.Invoke<int>("SingleResultFailure", 10, 20)
  79. .OnSuccess(result => uiText += string.Format(" 'SingleResultFailure(10, 20)' returned: {0}\n", result))
  80. .OnError(error => uiText += string.Format(" 'SingleResultFailure(10, 20)' error: {0}\n", error));
  81. // This call demonstrates IEnumerable<> functions, result will be the yielded numbers.
  82. hub.Invoke<int[]>("Batched", 10)
  83. .OnSuccess(result => uiText += string.Format(" 'Batched(10)' returned items: {0}\n", result.Length))
  84. .OnError(error => uiText += string.Format(" 'Batched(10)' error: {0}\n", error));
  85. // OnItem is called for a streaming request for every items returned by the server. OnSuccess will still be called with all the items.
  86. hub.Stream<int>("ObservableCounter", 10, 1000)
  87. .OnItem(result => uiText += string.Format(" 'ObservableCounter(10, 1000)' OnItem: {0}\n", result.LastAdded))
  88. .OnSuccess(result => uiText += string.Format(" 'ObservableCounter(10, 1000)' OnSuccess. Final count: {0}\n", result.Items.Count))
  89. .OnError(error => uiText += string.Format(" 'ObservableCounter(10, 1000)' error: {0}\n", error));
  90. // A stream request can be cancelled any time.
  91. var container = hub.Stream<int>("ChannelCounter", 10, 1000)
  92. .OnItem(result => uiText += string.Format(" 'ChannelCounter(10, 1000)' OnItem: {0}\n", result.LastAdded))
  93. .OnSuccess(result => uiText += string.Format(" 'ChannelCounter(10, 1000)' OnSuccess. Final count: {0}\n", result.Items.Count))
  94. .OnError(error => uiText += string.Format(" 'ChannelCounter(10, 1000)' error: {0}\n", error)).value;
  95. // a stream can be cancelled by calling CancelStream
  96. hub.CancelStream(container);
  97. // This call will stream strongly typed objects
  98. hub.Stream<Person>("GetRandomPersons", 20, 2000)
  99. .OnItem(result => uiText += string.Format(" 'GetRandomPersons(20, 1000)' OnItem: {0}\n", result.LastAdded))
  100. .OnSuccess(result => uiText += string.Format(" 'GetRandomPersons(20, 1000)' OnSuccess. Final count: {0}\n", result.Items.Count));
  101. }
  102. /// <summary>
  103. /// This callback is called for every hub message. If false is returned, the plugin will cancel any further processing of the message.
  104. /// </summary>
  105. private bool Hub_OnMessage(HubConnection hub, BestHTTP.SignalRCore.Messages.Message message)
  106. {
  107. //UnityEngine.Debug.Log("Message Arrived: " + message.ToString());
  108. return true;
  109. }
  110. /// <summary>
  111. /// This is called when the hub is closed after a StartClose() call.
  112. /// </summary>
  113. private void Hub_OnClosed(HubConnection hub)
  114. {
  115. uiText += "Hub Closed\n";
  116. }
  117. /// <summary>
  118. /// Called when an unrecoverable error happen. After this event the hub will not send or receive any messages.
  119. /// </summary>
  120. private void Hub_OnError(HubConnection hub, string error)
  121. {
  122. uiText += "Hub Error: " + error + "\n";
  123. }
  124. /// <summary>
  125. /// Helper class to demonstrate strongly typed callbacks
  126. /// </summary>
  127. sealed class Person
  128. {
  129. public string Name { get; set; }
  130. public long Age { get; set; }
  131. public override string ToString()
  132. {
  133. return string.Format("[Person Name: '{0}', Age: {1}]", this.Name, this.Age.ToString());
  134. }
  135. }
  136. }
  137. }
  138. #endif