WebSocket.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. #if !BESTHTTP_DISABLE_WEBSOCKET
  2. using System;
  3. using System.Text;
  4. using BestHTTP.Extensions;
  5. using BestHTTP.Connections;
  6. using BestHTTP.Logger;
  7. using BestHTTP.PlatformSupport.Memory;
  8. #if !UNITY_WEBGL || UNITY_EDITOR
  9. using BestHTTP.WebSocket.Frames;
  10. using BestHTTP.WebSocket.Extensions;
  11. #endif
  12. namespace BestHTTP.WebSocket
  13. {
  14. public sealed class WebSocket
  15. {
  16. /// <summary>
  17. /// Maximum payload size of a websocket frame. Its default value is 32 KiB.
  18. /// </summary>
  19. public static uint MaxFragmentSize = UInt16.MaxValue / 2;
  20. public WebSocketStates State { get { return this.implementation.State; } }
  21. /// <summary>
  22. /// The connection to the WebSocket server is open.
  23. /// </summary>
  24. public bool IsOpen { get { return this.implementation.IsOpen; } }
  25. /// <summary>
  26. /// Data waiting to be written to the wire.
  27. /// </summary>
  28. public int BufferedAmount { get { return this.implementation.BufferedAmount; } }
  29. #if !UNITY_WEBGL || UNITY_EDITOR
  30. /// <summary>
  31. /// Set to true to start a new thread to send Pings to the WebSocket server
  32. /// </summary>
  33. public bool StartPingThread { get; set; }
  34. /// <summary>
  35. /// The delay between two Pings in milliseconds. Minimum value is 100, default is 1000.
  36. /// </summary>
  37. public int PingFrequency { get; set; }
  38. /// <summary>
  39. /// If StartPingThread set to true, the plugin will close the connection and emit an OnError event if no
  40. /// message is received from the server in the given time. Its default value is 2 sec.
  41. /// </summary>
  42. public TimeSpan CloseAfterNoMessage { get; set; }
  43. /// <summary>
  44. /// The internal HTTPRequest object.
  45. /// </summary>
  46. public HTTPRequest InternalRequest { get { return this.implementation.InternalRequest; } }
  47. /// <summary>
  48. /// IExtension implementations the plugin will negotiate with the server to use.
  49. /// </summary>
  50. public IExtension[] Extensions { get; private set; }
  51. /// <summary>
  52. /// Latency calculated from the ping-pong message round-trip times.
  53. /// </summary>
  54. public int Latency { get { return this.implementation.Latency; } }
  55. /// <summary>
  56. /// When we received the last message from the server.
  57. /// </summary>
  58. public DateTime LastMessageReceived { get { return this.implementation.LastMessageReceived; } }
  59. /// <summary>
  60. /// When the Websocket Over HTTP/2 implementation fails to connect and EnableImplementationFallback is true, the plugin tries to fall back to the HTTP/1 implementation.
  61. /// When this happens a new InternalRequest is created and all previous custom modifications (like added headers) are lost. With OnInternalRequestCreated these modifications can be reapplied.
  62. /// </summary>
  63. public Action<WebSocket, HTTPRequest> OnInternalRequestCreated;
  64. #endif
  65. /// <summary>
  66. /// Called when the connection to the WebSocket server is established.
  67. /// </summary>
  68. public OnWebSocketOpenDelegate OnOpen;
  69. /// <summary>
  70. /// Called when a new textual message is received from the server.
  71. /// </summary>
  72. public OnWebSocketMessageDelegate OnMessage;
  73. /// <summary>
  74. /// Called when a new binary message is received from the server.
  75. /// </summary>
  76. public OnWebSocketBinaryDelegate OnBinary;
  77. /// <summary>
  78. /// Called when the WebSocket connection is closed.
  79. /// </summary>
  80. public OnWebSocketClosedDelegate OnClosed;
  81. /// <summary>
  82. /// Called when an error is encountered. The parameter will be the description of the error.
  83. /// </summary>
  84. public OnWebSocketErrorDelegate OnError;
  85. #if !UNITY_WEBGL || UNITY_EDITOR
  86. /// <summary>
  87. /// Called when an incomplete frame received. No attempt will be made to reassemble these fragments internally, and no reference are stored after this event to this frame.
  88. /// </summary>
  89. public OnWebSocketIncompleteFrameDelegate OnIncompleteFrame;
  90. #endif
  91. /// <summary>
  92. /// Logging context of this websocket instance.
  93. /// </summary>
  94. public LoggingContext Context { get; private set; }
  95. /// <summary>
  96. /// The underlying, real implementation.
  97. /// </summary>
  98. private WebSocketBaseImplementation implementation;
  99. /// <summary>
  100. /// Creates a WebSocket instance from the given uri.
  101. /// </summary>
  102. /// <param name="uri">The uri of the WebSocket server</param>
  103. public WebSocket(Uri uri)
  104. :this(uri, string.Empty, string.Empty)
  105. {
  106. #if (!UNITY_WEBGL || UNITY_EDITOR) && !BESTHTTP_DISABLE_GZIP
  107. this.Extensions = new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default,
  108. /*clientNoContextTakeover: */ false,
  109. /*serverNoContextTakeover: */ false,
  110. /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  111. /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  112. /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) };
  113. #endif
  114. }
  115. #if !UNITY_WEBGL || UNITY_EDITOR
  116. public WebSocket(Uri uri, string origin, string protocol)
  117. :this(uri, origin, protocol, null)
  118. {
  119. #if !BESTHTTP_DISABLE_GZIP
  120. this.Extensions = new IExtension[] { new PerMessageCompression(/*compression level: */ Decompression.Zlib.CompressionLevel.Default,
  121. /*clientNoContextTakeover: */ false,
  122. /*serverNoContextTakeover: */ false,
  123. /*clientMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  124. /*desiredServerMaxWindowBits: */ Decompression.Zlib.ZlibConstants.WindowBitsMax,
  125. /*minDatalengthToCompress: */ PerMessageCompression.MinDataLengthToCompressDefault) };
  126. #endif
  127. }
  128. #endif
  129. /// <summary>
  130. /// Creates a WebSocket instance from the given uri, protocol and origin.
  131. /// </summary>
  132. /// <param name="uri">The uri of the WebSocket server</param>
  133. /// <param name="origin">Servers that are not intended to process input from any web page but only for certain sites SHOULD verify the |Origin| field is an origin they expect.
  134. /// If the origin indicated is unacceptable to the server, then it SHOULD respond to the WebSocket handshake with a reply containing HTTP 403 Forbidden status code.</param>
  135. /// <param name="protocol">The application-level protocol that the client want to use(eg. "chat", "leaderboard", etc.). Can be null or empty string if not used.</param>
  136. /// <param name="extensions">Optional IExtensions implementations</param>
  137. public WebSocket(Uri uri, string origin, string protocol
  138. #if !UNITY_WEBGL || UNITY_EDITOR
  139. , params IExtension[] extensions
  140. #endif
  141. )
  142. {
  143. this.Context = new LoggingContext(this);
  144. #if !UNITY_WEBGL || UNITY_EDITOR
  145. this.Extensions = extensions;
  146. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && !BESTHTTP_DISABLE_HTTP2
  147. if (HTTPManager.HTTP2Settings.WebSocketOverHTTP2Settings.EnableWebSocketOverHTTP2 && HTTPProtocolFactory.IsSecureProtocol(uri))
  148. {
  149. // Try to find a HTTP/2 connection that supports the connect protocol.
  150. var con = BestHTTP.Core.HostManager.GetHost(uri.Host).GetHostDefinition(Core.HostDefinition.GetKeyFor(new UriBuilder("https", uri.Host, uri.Port).Uri
  151. #if !BESTHTTP_DISABLE_PROXY
  152. , GetProxy(uri)
  153. #endif
  154. )).Find(c => {
  155. var httpConnection = c as HTTPConnection;
  156. var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler;
  157. return http2Handler != null && http2Handler.settings.RemoteSettings[Connections.HTTP2.HTTP2Settings.ENABLE_CONNECT_PROTOCOL] != 0;
  158. });
  159. if (con != null)
  160. {
  161. HTTPManager.Logger.Information("WebSocket", "Connection with enabled Connect Protocol found!", this.Context);
  162. var httpConnection = con as HTTPConnection;
  163. var http2Handler = httpConnection?.requestHandler as Connections.HTTP2.HTTP2Handler;
  164. this.implementation = new OverHTTP2(this, http2Handler, uri, origin, protocol);
  165. }
  166. }
  167. #endif
  168. if (this.implementation == null)
  169. this.implementation = new OverHTTP1(this, uri, origin, protocol);
  170. #else
  171. this.implementation = new WebGLBrowser(this, uri, origin, protocol);
  172. #endif
  173. // Under WebGL when only the WebSocket protocol is used Setup() isn't called, so we have to call it here.
  174. HTTPManager.Setup();
  175. }
  176. #if !UNITY_WEBGL || UNITY_EDITOR
  177. internal void FallbackToHTTP1()
  178. {
  179. if (this.implementation == null)
  180. return;
  181. this.implementation = new OverHTTP1(this, this.implementation.Uri, this.implementation.Origin, this.implementation.Protocol);
  182. this.implementation.StartOpen();
  183. }
  184. #endif
  185. /// <summary>
  186. /// Start the opening process.
  187. /// </summary>
  188. public void Open()
  189. {
  190. this.implementation.StartOpen();
  191. }
  192. /// <summary>
  193. /// It will send the given message to the server in one frame.
  194. /// </summary>
  195. public void Send(string message)
  196. {
  197. if (!IsOpen)
  198. return;
  199. this.implementation.Send(message);
  200. }
  201. /// <summary>
  202. /// It will send the given data to the server in one frame.
  203. /// </summary>
  204. public void Send(byte[] buffer)
  205. {
  206. if (!IsOpen)
  207. return;
  208. this.implementation.Send(buffer);
  209. }
  210. /// <summary>
  211. /// Will send count bytes from a byte array, starting from offset.
  212. /// </summary>
  213. public void Send(byte[] buffer, ulong offset, ulong count)
  214. {
  215. if (!IsOpen)
  216. return;
  217. this.implementation.Send(buffer, offset, count);
  218. }
  219. #if !UNITY_WEBGL || UNITY_EDITOR
  220. /// <summary>
  221. /// It will send the given frame to the server.
  222. /// </summary>
  223. public void Send(WebSocketFrame frame)
  224. {
  225. if (!IsOpen)
  226. return;
  227. this.implementation.Send(frame);
  228. }
  229. #endif
  230. /// <summary>
  231. /// It will initiate the closing of the connection to the server.
  232. /// </summary>
  233. public void Close()
  234. {
  235. if (State >= WebSocketStates.Closing)
  236. return;
  237. this.implementation.StartClose(1000, "Bye!");
  238. }
  239. /// <summary>
  240. /// It will initiate the closing of the connection to the server sending the given code and message.
  241. /// </summary>
  242. public void Close(UInt16 code, string message)
  243. {
  244. if (!IsOpen)
  245. return;
  246. this.implementation.StartClose(code, message);
  247. }
  248. #if !BESTHTTP_DISABLE_PROXY
  249. internal Proxy GetProxy(Uri uri)
  250. {
  251. // WebSocket is not a request-response based protocol, so we need a 'tunnel' through the proxy
  252. HTTPProxy proxy = HTTPManager.Proxy as HTTPProxy;
  253. if (proxy != null && proxy.UseProxyForAddress(uri))
  254. proxy = new HTTPProxy(proxy.Address,
  255. proxy.Credentials,
  256. false, /*turn on 'tunneling'*/
  257. false, /*sendWholeUri*/
  258. proxy.NonTransparentForHTTPS);
  259. return proxy;
  260. }
  261. #endif
  262. #if !UNITY_WEBGL || UNITY_EDITOR
  263. public static byte[] EncodeCloseData(UInt16 code, string message)
  264. {
  265. //If there is a body, the first two bytes of the body MUST be a 2-byte unsigned integer
  266. // (in network byte order) representing a status code with value /code/ defined in Section 7.4 (http://tools.ietf.org/html/rfc6455#section-7.4). Following the 2-byte integer,
  267. // the body MAY contain UTF-8-encoded data with value /reason/, the interpretation of which is not defined by this specification.
  268. // This data is not necessarily human readable but may be useful for debugging or passing information relevant to the script that opened the connection.
  269. int msgLen = Encoding.UTF8.GetByteCount(message);
  270. using (var ms = new BufferPoolMemoryStream(2 + msgLen))
  271. {
  272. byte[] buff = BitConverter.GetBytes(code);
  273. if (BitConverter.IsLittleEndian)
  274. Array.Reverse(buff, 0, buff.Length);
  275. ms.Write(buff, 0, buff.Length);
  276. buff = Encoding.UTF8.GetBytes(message);
  277. ms.Write(buff, 0, buff.Length);
  278. return ms.ToArray();
  279. }
  280. }
  281. internal static string GetSecKey(object[] from)
  282. {
  283. const int keysLength = 16;
  284. byte[] keys = BufferPool.Get(keysLength, true);
  285. int pos = 0;
  286. for (int i = 0; i < from.Length; ++i)
  287. {
  288. byte[] hash = BitConverter.GetBytes((Int32)from[i].GetHashCode());
  289. for (int cv = 0; cv < hash.Length && pos < keysLength; ++cv)
  290. keys[pos++] = hash[cv];
  291. }
  292. var result = Convert.ToBase64String(keys, 0, keysLength);
  293. BufferPool.Release(keys);
  294. return result;
  295. }
  296. #endif
  297. }
  298. }
  299. #endif