SimpleStreamingSample.cs 2.2 KB

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