WebSocketSample.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #if !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using BestHTTP.Examples.Helpers;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. namespace BestHTTP.Examples.Websockets
  7. {
  8. public class WebSocketSample : BestHTTP.Examples.Helpers.SampleBase
  9. {
  10. #pragma warning disable 0649
  11. [SerializeField]
  12. [Tooltip("The WebSocket address to connect")]
  13. private string address = "wss://besthttpwebgldemo.azurewebsites.net/ws";
  14. [SerializeField]
  15. private InputField _input;
  16. [SerializeField]
  17. private ScrollRect _scrollRect;
  18. [SerializeField]
  19. private RectTransform _contentRoot;
  20. [SerializeField]
  21. private TextListItem _listItemPrefab;
  22. [SerializeField]
  23. private int _maxListItemEntries = 100;
  24. [SerializeField]
  25. private Button _connectButton;
  26. [SerializeField]
  27. private Button _closeButton;
  28. #pragma warning restore
  29. /// <summary>
  30. /// Saved WebSocket instance
  31. /// </summary>
  32. WebSocket.WebSocket webSocket;
  33. protected override void Start()
  34. {
  35. base.Start();
  36. SetButtons(true, false);
  37. this._input.interactable = false;
  38. }
  39. void OnDestroy()
  40. {
  41. if (this.webSocket != null)
  42. {
  43. this.webSocket.Close();
  44. this.webSocket = null;
  45. }
  46. }
  47. public void OnConnectButton()
  48. {
  49. // Create the WebSocket instance
  50. this.webSocket = new WebSocket.WebSocket(new Uri(address));
  51. #if !UNITY_WEBGL || UNITY_EDITOR
  52. this.webSocket.StartPingThread = true;
  53. #if !BESTHTTP_DISABLE_PROXY
  54. if (HTTPManager.Proxy != null)
  55. this.webSocket.OnInternalRequestCreated = (ws, internalRequest) => internalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
  56. #endif
  57. #endif
  58. // Subscribe to the WS events
  59. this.webSocket.OnOpen += OnOpen;
  60. this.webSocket.OnMessage += OnMessageReceived;
  61. this.webSocket.OnClosed += OnClosed;
  62. this.webSocket.OnError += OnError;
  63. // Start connecting to the server
  64. this.webSocket.Open();
  65. AddText("Connecting...");
  66. SetButtons(false, true);
  67. this._input.interactable = false;
  68. }
  69. public void OnCloseButton()
  70. {
  71. AddText("Closing!");
  72. // Close the connection
  73. this.webSocket.Close(1000, "Bye!");
  74. SetButtons(false, false);
  75. this._input.interactable = false;
  76. }
  77. public void OnInputField(string textToSend)
  78. {
  79. if ((!Input.GetKeyDown(KeyCode.KeypadEnter) && !Input.GetKeyDown(KeyCode.Return)) || string.IsNullOrEmpty(textToSend))
  80. return;
  81. AddText(string.Format("Sending message: <color=green>{0}</color>", textToSend))
  82. .AddLeftPadding(20);
  83. // Send message to the server
  84. this.webSocket.Send(textToSend);
  85. }
  86. #region WebSocket Event Handlers
  87. /// <summary>
  88. /// Called when the web socket is open, and we are ready to send and receive data
  89. /// </summary>
  90. void OnOpen(WebSocket.WebSocket ws)
  91. {
  92. AddText("WebSocket Open!");
  93. this._input.interactable = true;
  94. }
  95. /// <summary>
  96. /// Called when we received a text message from the server
  97. /// </summary>
  98. void OnMessageReceived(WebSocket.WebSocket ws, string message)
  99. {
  100. AddText(string.Format("Message received: <color=yellow>{0}</color>", message))
  101. .AddLeftPadding(20);
  102. }
  103. /// <summary>
  104. /// Called when the web socket closed
  105. /// </summary>
  106. void OnClosed(WebSocket.WebSocket ws, UInt16 code, string message)
  107. {
  108. AddText(string.Format("WebSocket closed! Code: {0} Message: {1}", code, message));
  109. webSocket = null;
  110. SetButtons(true, false);
  111. }
  112. /// <summary>
  113. /// Called when an error occured on client side
  114. /// </summary>
  115. void OnError(WebSocket.WebSocket ws, string error)
  116. {
  117. AddText(string.Format("An error occured: <color=red>{0}</color>", error));
  118. webSocket = null;
  119. SetButtons(true, false);
  120. }
  121. #endregion
  122. private void SetButtons(bool connect, bool close)
  123. {
  124. if (this._connectButton != null)
  125. this._connectButton.interactable = connect;
  126. if (this._closeButton != null)
  127. this._closeButton.interactable = close;
  128. }
  129. private TextListItem AddText(string text)
  130. {
  131. return GUIHelper.AddText(this._listItemPrefab, this._contentRoot, text, this._maxListItemEntries, this._scrollRect);
  132. }
  133. }
  134. }
  135. #endif