SimpleStreamingSample.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #if !BESTHTTP_DISABLE_SIGNALR
  2. using System;
  3. using UnityEngine;
  4. using BestHTTP.SignalR;
  5. namespace BestHTTP.Examples
  6. {
  7. public sealed class SimpleStreamingSample : MonoBehaviour
  8. {
  9. readonly Uri URI = new Uri(GUIHelper.BaseURL + "/streaming-connection");
  10. /// <summary>
  11. /// Reference to the SignalR Connection
  12. /// </summary>
  13. Connection signalRConnection;
  14. /// <summary>
  15. /// Helper GUI class to handle and display a string-list
  16. /// </summary>
  17. GUIMessageList messages = new GUIMessageList();
  18. #region Unity Events
  19. void Start()
  20. {
  21. // Create the SignalR connection
  22. signalRConnection = new Connection(URI);
  23. // set event handlers
  24. signalRConnection.OnNonHubMessage += signalRConnection_OnNonHubMessage;
  25. signalRConnection.OnStateChanged += signalRConnection_OnStateChanged;
  26. signalRConnection.OnError += signalRConnection_OnError;
  27. // Start connecting to the server
  28. signalRConnection.Open();
  29. }
  30. void OnDestroy()
  31. {
  32. // Close the connection when the sample is closed
  33. signalRConnection.Close();
  34. }
  35. void OnGUI()
  36. {
  37. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  38. {
  39. GUILayout.Label("Messages");
  40. GUILayout.BeginHorizontal();
  41. GUILayout.Space(20);
  42. messages.Draw(Screen.width - 20, 0);
  43. GUILayout.EndHorizontal();
  44. });
  45. }
  46. #endregion
  47. #region SignalR Events
  48. /// <summary>
  49. /// Handle Server-sent messages
  50. /// </summary>
  51. void signalRConnection_OnNonHubMessage(Connection connection, object data)
  52. {
  53. messages.Add("[Server Message] " + data.ToString());
  54. }
  55. /// <summary>
  56. /// Display state changes
  57. /// </summary>
  58. void signalRConnection_OnStateChanged(Connection connection, ConnectionStates oldState, ConnectionStates newState)
  59. {
  60. messages.Add(string.Format("[State Change] {0} => {1}", oldState, newState));
  61. }
  62. /// <summary>
  63. /// Display errors.
  64. /// </summary>
  65. void signalRConnection_OnError(Connection connection, string error)
  66. {
  67. messages.Add("[Error] " + error);
  68. }
  69. #endregion
  70. }
  71. }
  72. #endif