WebGLBrowser.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #if (UNITY_WEBGL && !UNITY_EDITOR) && !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.InteropServices;
  5. using BestHTTP.PlatformSupport.Memory;
  6. namespace BestHTTP.WebSocket
  7. {
  8. delegate void OnWebGLWebSocketOpenDelegate(uint id);
  9. delegate void OnWebGLWebSocketTextDelegate(uint id, string text);
  10. delegate void OnWebGLWebSocketBinaryDelegate(uint id, IntPtr pBuffer, int length);
  11. delegate void OnWebGLWebSocketErrorDelegate(uint id, string error);
  12. delegate void OnWebGLWebSocketCloseDelegate(uint id, int code, string reason);
  13. internal sealed class WebGLBrowser : WebSocketBaseImplementation
  14. {
  15. public override WebSocketStates State => ImplementationId != 0 ? WS_GetState(ImplementationId) : WebSocketStates.Unknown;
  16. public override bool IsOpen => ImplementationId != 0 && WS_GetState(ImplementationId) == WebSocketStates.Open;
  17. public override int BufferedAmount => WS_GetBufferedAmount(ImplementationId);
  18. internal static Dictionary<uint, WebSocket> WebSockets = new Dictionary<uint, WebSocket>();
  19. private uint ImplementationId;
  20. public WebGLBrowser(WebSocket parent, Uri uri, string origin, string protocol) : base(parent, uri, origin, protocol)
  21. {
  22. }
  23. public override void StartOpen()
  24. {
  25. try
  26. {
  27. ImplementationId = WS_Create(this.Uri.OriginalString, this.Protocol, OnOpenCallback, OnTextCallback, OnBinaryCallback, OnErrorCallback, OnCloseCallback);
  28. WebSockets.Add(ImplementationId, this.Parent);
  29. }
  30. catch(Exception ex)
  31. {
  32. HTTPManager.Logger.Exception("WebSocket", "Open", ex, this.Parent.Context);
  33. }
  34. }
  35. public override void StartClose(UInt16 code, string message)
  36. {
  37. WS_Close(this.ImplementationId, code, message);
  38. }
  39. public override void Send(string message)
  40. {
  41. var count = System.Text.Encoding.UTF8.GetByteCount(message);
  42. var buffer = BufferPool.Get(count, true);
  43. System.Text.Encoding.UTF8.GetBytes(message, 0, message.Length, buffer, 0);
  44. WS_Send_String(this.ImplementationId, buffer, 0, count);
  45. BufferPool.Release(buffer);
  46. }
  47. public override void Send(byte[] buffer)
  48. {
  49. WS_Send_Binary(this.ImplementationId, buffer, 0, buffer.Length);
  50. }
  51. public override void Send(byte[] buffer, ulong offset, ulong count)
  52. {
  53. WS_Send_Binary(this.ImplementationId, buffer, (int)offset, (int)count);
  54. }
  55. public override void SendAsBinary(BufferSegment data)
  56. {
  57. WS_Send_Binary(this.ImplementationId, data.Data, data.Offset, data.Count);
  58. BufferPool.Release(data);
  59. }
  60. public override void SendAsText(BufferSegment data)
  61. {
  62. WS_Send_String(this.ImplementationId, data.Data, data.Offset, data.Count);
  63. BufferPool.Release(data);
  64. }
  65. [DllImport("__Internal")]
  66. static extern uint WS_Create(string url, string protocol, OnWebGLWebSocketOpenDelegate onOpen, OnWebGLWebSocketTextDelegate onText, OnWebGLWebSocketBinaryDelegate onBinary, OnWebGLWebSocketErrorDelegate onError, OnWebGLWebSocketCloseDelegate onClose);
  67. [DllImport("__Internal")]
  68. static extern WebSocketStates WS_GetState(uint id);
  69. [DllImport("__Internal")]
  70. static extern int WS_GetBufferedAmount(uint id);
  71. [DllImport("__Internal")]
  72. static extern int WS_Send_String(uint id, byte[] strData, int pos, int length);
  73. [DllImport("__Internal")]
  74. static extern int WS_Send_Binary(uint id, byte[] buffer, int pos, int length);
  75. [DllImport("__Internal")]
  76. static extern void WS_Close(uint id, ushort code, string reason);
  77. [DllImport("__Internal")]
  78. static extern void WS_Release(uint id);
  79. [AOT.MonoPInvokeCallback(typeof(OnWebGLWebSocketOpenDelegate))]
  80. static void OnOpenCallback(uint id)
  81. {
  82. WebSocket ws;
  83. if (WebSockets.TryGetValue(id, out ws))
  84. {
  85. if (ws.OnOpen != null)
  86. {
  87. try
  88. {
  89. ws.OnOpen(ws);
  90. }
  91. catch(Exception ex)
  92. {
  93. HTTPManager.Logger.Exception("WebSocket", "OnOpen", ex, ws.Context);
  94. }
  95. }
  96. }
  97. else
  98. HTTPManager.Logger.Warning("WebSocket", "OnOpenCallback - No WebSocket found for id: " + id.ToString(), ws.Context);
  99. }
  100. [AOT.MonoPInvokeCallback(typeof(OnWebGLWebSocketTextDelegate))]
  101. static void OnTextCallback(uint id, string text)
  102. {
  103. WebSocket ws;
  104. if (WebSockets.TryGetValue(id, out ws))
  105. {
  106. if (ws.OnMessage != null)
  107. {
  108. try
  109. {
  110. ws.OnMessage(ws, text);
  111. }
  112. catch (Exception ex)
  113. {
  114. HTTPManager.Logger.Exception("WebSocket", "OnMessage", ex, ws.Context);
  115. }
  116. }
  117. }
  118. else
  119. HTTPManager.Logger.Warning("WebSocket", "OnTextCallback - No WebSocket found for id: " + id.ToString());
  120. }
  121. [AOT.MonoPInvokeCallback(typeof(OnWebGLWebSocketBinaryDelegate))]
  122. static void OnBinaryCallback(uint id, IntPtr pBuffer, int length)
  123. {
  124. WebSocket ws;
  125. if (WebSockets.TryGetValue(id, out ws))
  126. {
  127. if (ws.OnBinary != null)
  128. {
  129. try
  130. {
  131. byte[] buffer = new byte[length];
  132. // Copy data from the 'unmanaged' memory to managed memory. Buffer will be reclaimed by the GC.
  133. Marshal.Copy(pBuffer, buffer, 0, length);
  134. ws.OnBinary(ws, buffer);
  135. }
  136. catch (Exception ex)
  137. {
  138. HTTPManager.Logger.Exception("WebSocket", "OnBinary", ex, ws.Context);
  139. }
  140. }
  141. if (ws.OnBinaryNoAlloc != null)
  142. {
  143. try
  144. {
  145. byte[] buffer = BufferPool.Get(length, true);
  146. // We still have to do a copy here, but at least the buffer will be released back to the pool.
  147. // Copy data from the 'unmanaged' memory to managed memory. Buffer will be reclaimed by the GC.
  148. Marshal.Copy(pBuffer, buffer, 0, length);
  149. ws.OnBinaryNoAlloc(ws, new BufferSegment(buffer, 0, length));
  150. BufferPool.Release(buffer);
  151. }
  152. catch (Exception ex)
  153. {
  154. HTTPManager.Logger.Exception("WebSocket", "OnBinary", ex, ws.Context);
  155. }
  156. }
  157. }
  158. else
  159. HTTPManager.Logger.Warning("WebSocket", "OnBinaryCallback - No WebSocket found for id: " + id.ToString());
  160. }
  161. [AOT.MonoPInvokeCallback(typeof(OnWebGLWebSocketErrorDelegate))]
  162. static void OnErrorCallback(uint id, string error)
  163. {
  164. WebSocket ws;
  165. if (WebSockets.TryGetValue(id, out ws))
  166. {
  167. WebSockets.Remove(id);
  168. if (ws.OnError != null)
  169. {
  170. try
  171. {
  172. ws.OnError(ws, error);
  173. }
  174. catch (Exception ex)
  175. {
  176. HTTPManager.Logger.Exception("WebSocket", "OnError", ex, ws.Context);
  177. }
  178. }
  179. }
  180. else
  181. HTTPManager.Logger.Warning("WebSocket", "OnErrorCallback - No WebSocket found for id: " + id.ToString());
  182. try
  183. {
  184. WS_Release(id);
  185. }
  186. catch(Exception ex)
  187. {
  188. HTTPManager.Logger.Exception("WebSocket", "WS_Release", ex);
  189. }
  190. }
  191. [AOT.MonoPInvokeCallback(typeof(OnWebGLWebSocketCloseDelegate))]
  192. static void OnCloseCallback(uint id, int code, string reason)
  193. {
  194. // To match non-webgl behavior, we have to treat this client-side generated message as an error
  195. if (code == (int)WebSocketStausCodes.ClosedAbnormally)
  196. {
  197. OnErrorCallback(id, "Abnormal disconnection.");
  198. return;
  199. }
  200. WebSocket ws;
  201. if (WebSockets.TryGetValue(id, out ws))
  202. {
  203. WebSockets.Remove(id);
  204. if (ws.OnClosed != null)
  205. {
  206. try
  207. {
  208. ws.OnClosed(ws, (ushort)code, reason);
  209. }
  210. catch (Exception ex)
  211. {
  212. HTTPManager.Logger.Exception("WebSocket", "OnClosed", ex, ws.Context);
  213. }
  214. }
  215. }
  216. else
  217. HTTPManager.Logger.Warning("WebSocket", "OnCloseCallback - No WebSocket found for id: " + id.ToString());
  218. try
  219. {
  220. WS_Release(id);
  221. }
  222. catch(Exception ex)
  223. {
  224. HTTPManager.Logger.Exception("WebSocket", "WS_Release", ex);
  225. }
  226. }
  227. }
  228. }
  229. #endif