WebSocketSample.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. #if !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using UnityEngine;
  4. using BestHTTP;
  5. using BestHTTP.WebSocket;
  6. using BestHTTP.Examples;
  7. using System.Text;
  8. public class WebSocketSample : MonoBehaviour
  9. {
  10. #region Private Fields
  11. /// <summary>
  12. /// The WebSocket address to connect
  13. /// </summary>
  14. string address = "wss://rtc.shadowcreator.com:3300";
  15. /// <summary>
  16. /// Default text to send
  17. /// </summary>
  18. string msgToSend = "Hello World!";
  19. /// <summary>
  20. /// Debug text to draw on the gui
  21. /// </summary>
  22. string Text = string.Empty;
  23. /// <summary>
  24. /// Saved WebSocket instance
  25. /// </summary>
  26. WebSocket webSocket;
  27. /// <summary>
  28. /// GUI scroll position
  29. /// </summary>
  30. Vector2 scrollPos;
  31. #endregion
  32. #region Unity Events
  33. void OnDestroy()
  34. {
  35. if (webSocket != null)
  36. webSocket.Close();
  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(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.OnBinary += OnBinaryReceived;
  63. webSocket.OnClosed += OnClosed;
  64. webSocket.OnError += OnError;
  65. // Start connecting to the server
  66. webSocket.Open();
  67. Text += "Opening Web Socket...\n";
  68. }
  69. if (webSocket != null && webSocket.IsOpen)
  70. {
  71. GUILayout.Space(10);
  72. GUILayout.BeginHorizontal();
  73. msgToSend = GUILayout.TextField(msgToSend);
  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.EndHorizontal();
  81. GUILayout.Space(10);
  82. if (GUILayout.Button("Close"))
  83. {
  84. // Close the connection
  85. webSocket.Close(1000, "Bye!");
  86. }
  87. }
  88. });
  89. }
  90. #endregion
  91. #region WebSocket Event Handlers
  92. /// <summary>
  93. /// Called when the web socket is open, and we are ready to send and receive data
  94. /// </summary>
  95. void OnOpen(WebSocket ws)
  96. {
  97. Text += string.Format("-WebSocket Open!\n");
  98. }
  99. /// <summary>
  100. /// Called when we received a text message from the server
  101. /// </summary>
  102. void OnMessageReceived(WebSocket ws, string message)
  103. {
  104. Text += string.Format("-Message received: {0}\n", message);
  105. }
  106. /// <summary>
  107. /// Called when we received a text message from the server
  108. /// </summary>
  109. void OnBinaryReceived(WebSocket webSocket, byte[] data)
  110. {
  111. // string str = Encoding.UTF8.GetString (data);
  112. Debug.Log (string.Format("-Binary received: {0}\n", data.Length));
  113. // Text += string.Format("-Binary received: {0}\n", str);
  114. }
  115. /// <summary>
  116. /// Called when the web socket closed
  117. /// </summary>
  118. void OnClosed(WebSocket ws, UInt16 code, string message)
  119. {
  120. Text += string.Format("-WebSocket closed! Code: {0} Message: {1}\n", code, message);
  121. webSocket = null;
  122. }
  123. /// <summary>
  124. /// Called when an error occured on client side
  125. /// </summary>
  126. void OnError(WebSocket ws, Exception ex)
  127. {
  128. string errorMsg = string.Empty;
  129. #if !UNITY_WEBGL || UNITY_EDITOR
  130. if (ws.InternalRequest.Response != null)
  131. errorMsg = string.Format("Status Code from Server: {0} and Message: {1}", ws.InternalRequest.Response.StatusCode, ws.InternalRequest.Response.Message);
  132. #endif
  133. Text += string.Format("-An error occured: {0}\n", (ex != null ? ex.Message : "Unknown Error " + errorMsg));
  134. webSocket = null;
  135. }
  136. #endregion
  137. }
  138. #endif