WebSocketSample.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #if !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using UnityEngine;
  4. namespace BestHTTP.Examples
  5. {
  6. public class WebSocketSample : MonoBehaviour
  7. {
  8. #region Private Fields
  9. /// <summary>
  10. /// The WebSocket address to connect
  11. /// </summary>
  12. string address = "wss://echo.websocket.org";
  13. /// <summary>
  14. /// Default text to send
  15. /// </summary>
  16. string msgToSend = "Hello World!";
  17. /// <summary>
  18. /// Debug text to draw on the gui
  19. /// </summary>
  20. string Text = string.Empty;
  21. /// <summary>
  22. /// Saved WebSocket instance
  23. /// </summary>
  24. WebSocket.WebSocket webSocket;
  25. /// <summary>
  26. /// GUI scroll position
  27. /// </summary>
  28. Vector2 scrollPos;
  29. #endregion
  30. #region Unity Events
  31. void OnDestroy()
  32. {
  33. if (webSocket != null)
  34. {
  35. webSocket.Close();
  36. }
  37. }
  38. void OnGUI()
  39. {
  40. GUIHelper.DrawArea(GUIHelper.ClientArea, true, () =>
  41. {
  42. scrollPos = GUILayout.BeginScrollView(scrollPos);
  43. GUILayout.Label(Text);
  44. GUILayout.EndScrollView();
  45. GUILayout.Space(5);
  46. GUILayout.FlexibleSpace();
  47. address = GUILayout.TextField(address);
  48. if (webSocket == null && GUILayout.Button("Open Web Socket"))
  49. {
  50. // Create the WebSocket instance
  51. webSocket = new WebSocket.WebSocket(new Uri(address));
  52. #if !UNITY_WEBGL
  53. webSocket.StartPingThread = true;
  54. #if !BESTHTTP_DISABLE_PROXY
  55. if (HTTPManager.Proxy != null)
  56. webSocket.InternalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address, HTTPManager.Proxy.Credentials, false);
  57. #endif
  58. #endif
  59. // Subscribe to the WS events
  60. webSocket.OnOpen += OnOpen;
  61. webSocket.OnMessage += OnMessageReceived;
  62. webSocket.OnClosed += OnClosed;
  63. webSocket.OnError += OnError;
  64. // Start connecting to the server
  65. webSocket.Open();
  66. Text += "Opening Web Socket...\n";
  67. }
  68. if (webSocket != null && webSocket.IsOpen)
  69. {
  70. GUILayout.Space(10);
  71. GUILayout.BeginHorizontal();
  72. msgToSend = GUILayout.TextField(msgToSend);
  73. GUILayout.EndHorizontal();
  74. if (GUILayout.Button("Send", GUILayout.MaxWidth(70)))
  75. {
  76. Text += "Sending message...\n";
  77. // Send message to the server
  78. webSocket.Send(msgToSend);
  79. }
  80. GUILayout.Space(10);
  81. if (GUILayout.Button("Close"))
  82. {
  83. // Close the connection
  84. webSocket.Close(1000, "Bye!");
  85. }
  86. }
  87. });
  88. }
  89. #endregion
  90. #region WebSocket Event Handlers
  91. /// <summary>
  92. /// Called when the web socket is open, and we are ready to send and receive data
  93. /// </summary>
  94. void OnOpen(WebSocket.WebSocket ws)
  95. {
  96. Text += string.Format("-WebSocket Open!\n");
  97. }
  98. /// <summary>
  99. /// Called when we received a text message from the server
  100. /// </summary>
  101. void OnMessageReceived(WebSocket.WebSocket ws, string message)
  102. {
  103. Text += string.Format("-Message received: {0}\n", message);
  104. }
  105. /// <summary>
  106. /// Called when the web socket closed
  107. /// </summary>
  108. void OnClosed(WebSocket.WebSocket ws, UInt16 code, string message)
  109. {
  110. Text += string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
  111. webSocket = null;
  112. }
  113. /// <summary>
  114. /// Called when an error occured on client side
  115. /// </summary>
  116. void OnError(WebSocket.WebSocket ws, Exception ex)
  117. {
  118. string errorMsg = string.Empty;
  119. #if !UNITY_WEBGL || UNITY_EDITOR
  120. if (ws.InternalRequest.Response != null)
  121. {
  122. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  123. }
  124. #endif
  125. Text += string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  126. webSocket = null;
  127. }
  128. #endregion
  129. }
  130. }
  131. #endif