WebSocketTransport.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. #if !BESTHTTP_DISABLE_SOCKETIO
  2. #if !BESTHTTP_DISABLE_WEBSOCKET
  3. using System;
  4. using System.Collections.Generic;
  5. namespace BestHTTP.SocketIO.Transports
  6. {
  7. using BestHTTP.Connections;
  8. using BestHTTP.WebSocket;
  9. using Extensions;
  10. /// <summary>
  11. /// A transport implementation that can communicate with a SocketIO server.
  12. /// </summary>
  13. internal sealed class WebSocketTransport : ITransport
  14. {
  15. public TransportTypes Type { get { return TransportTypes.WebSocket; } }
  16. public TransportStates State { get; private set; }
  17. public SocketManager Manager { get; private set; }
  18. public bool IsRequestInProgress { get { return false; } }
  19. public bool IsPollingInProgress { get { return false; } }
  20. public WebSocket Implementation { get; private set; }
  21. private Packet PacketWithAttachment;
  22. private byte[] Buffer;
  23. public WebSocketTransport(SocketManager manager)
  24. {
  25. State = TransportStates.Closed;
  26. Manager = manager;
  27. }
  28. #region Some ITransport Implementation
  29. public void Open()
  30. {
  31. if (State != TransportStates.Closed)
  32. return;
  33. Uri uri = null;
  34. string baseUrl = new UriBuilder(HTTPProtocolFactory.IsSecureProtocol(Manager.Uri) ? "wss" : "ws",
  35. Manager.Uri.Host,
  36. Manager.Uri.Port,
  37. Manager.Uri.GetRequestPathAndQueryURL()).Uri.ToString();
  38. string format = "{0}?EIO={1}&transport=websocket{3}";
  39. if (Manager.Handshake != null)
  40. format += "&sid={2}";
  41. bool sendAdditionalQueryParams = !Manager.Options.QueryParamsOnlyForHandshake || (Manager.Options.QueryParamsOnlyForHandshake && Manager.Handshake == null);
  42. uri = new Uri(string.Format(format,
  43. baseUrl,
  44. Manager.ProtocolVersion,
  45. Manager.Handshake != null ? Manager.Handshake.Sid : string.Empty,
  46. sendAdditionalQueryParams ? Manager.Options.BuildQueryParams() : string.Empty));
  47. Implementation = new WebSocket(uri);
  48. #if !UNITY_WEBGL || UNITY_EDITOR
  49. Implementation.StartPingThread = true;
  50. if (this.Manager.Options.HTTPRequestCustomizationCallback != null)
  51. Implementation.OnInternalRequestCreated = (ws, internalRequest) => this.Manager.Options.HTTPRequestCustomizationCallback(this.Manager, internalRequest);
  52. #endif
  53. Implementation.OnOpen = OnOpen;
  54. Implementation.OnMessage = OnMessage;
  55. Implementation.OnBinary = OnBinary;
  56. Implementation.OnError = OnError;
  57. Implementation.OnClosed = OnClosed;
  58. Implementation.Open();
  59. State = TransportStates.Connecting;
  60. }
  61. /// <summary>
  62. /// Closes the transport and cleans up resources.
  63. /// </summary>
  64. public void Close()
  65. {
  66. if (State == TransportStates.Closed)
  67. return;
  68. State = TransportStates.Closed;
  69. if (Implementation != null)
  70. Implementation.Close();
  71. else
  72. HTTPManager.Logger.Warning("WebSocketTransport", "Close - WebSocket Implementation already null!");
  73. Implementation = null;
  74. }
  75. /// <summary>
  76. /// Polling implementation. With WebSocket it's just a skeleton.
  77. /// </summary>
  78. public void Poll()
  79. {
  80. }
  81. #endregion
  82. #region WebSocket Events
  83. /// <summary>
  84. /// WebSocket implementation OnOpen event handler.
  85. /// </summary>
  86. private void OnOpen(WebSocket ws)
  87. {
  88. if (ws != Implementation)
  89. return;
  90. HTTPManager.Logger.Information("WebSocketTransport", "OnOpen");
  91. State = TransportStates.Opening;
  92. // Send a Probe packet to test the transport. If we receive back a pong with the same payload we can upgrade
  93. if (Manager.UpgradingTransport == this)
  94. Send(new Packet(TransportEventTypes.Ping, SocketIOEventTypes.Unknown, "/", "probe"));
  95. }
  96. /// <summary>
  97. /// WebSocket implementation OnMessage event handler.
  98. /// </summary>
  99. private void OnMessage(WebSocket ws, string message)
  100. {
  101. if (ws != Implementation)
  102. return;
  103. if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
  104. HTTPManager.Logger.Verbose("WebSocketTransport", "OnMessage: " + message);
  105. Packet packet = null;
  106. try
  107. {
  108. packet = new Packet(message);
  109. }
  110. catch (Exception ex)
  111. {
  112. HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage Packet parsing", ex);
  113. }
  114. if (packet == null)
  115. {
  116. HTTPManager.Logger.Error("WebSocketTransport", "Message parsing failed. Message: " + message);
  117. return;
  118. }
  119. try
  120. {
  121. if (packet.AttachmentCount == 0)
  122. OnPacket(packet);
  123. else
  124. PacketWithAttachment = packet;
  125. }
  126. catch (Exception ex)
  127. {
  128. HTTPManager.Logger.Exception("WebSocketTransport", "OnMessage OnPacket", ex);
  129. }
  130. }
  131. /// <summary>
  132. /// WebSocket implementation OnBinary event handler.
  133. /// </summary>
  134. private void OnBinary(WebSocket ws, byte[] data)
  135. {
  136. if (ws != Implementation)
  137. return;
  138. if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
  139. HTTPManager.Logger.Verbose("WebSocketTransport", "OnBinary");
  140. if (PacketWithAttachment != null)
  141. {
  142. switch(this.Manager.Options.ServerVersion)
  143. {
  144. case SupportedSocketIOVersions.v2: PacketWithAttachment.AddAttachmentFromServer(data, false); break;
  145. case SupportedSocketIOVersions.v3: PacketWithAttachment.AddAttachmentFromServer(data, true); break;
  146. default:
  147. HTTPManager.Logger.Warning("WebSocketTransport", "Binary packet received while the server's version is Unknown. Set SocketOption's ServerVersion to the correct value to avoid packet mishandling!");
  148. // Fall back to V2 by default.
  149. this.Manager.Options.ServerVersion = SupportedSocketIOVersions.v2;
  150. goto case SupportedSocketIOVersions.v2;
  151. }
  152. if (PacketWithAttachment.HasAllAttachment)
  153. {
  154. try
  155. {
  156. OnPacket(PacketWithAttachment);
  157. }
  158. catch (Exception ex)
  159. {
  160. HTTPManager.Logger.Exception("WebSocketTransport", "OnBinary", ex);
  161. }
  162. finally
  163. {
  164. PacketWithAttachment = null;
  165. }
  166. }
  167. }
  168. else
  169. {
  170. // Room for improvement: we received an unwanted binary message?
  171. }
  172. }
  173. /// <summary>
  174. /// WebSocket implementation OnError event handler.
  175. /// </summary>
  176. private void OnError(WebSocket ws, string error)
  177. {
  178. if (ws != Implementation)
  179. return;
  180. #if !UNITY_WEBGL || UNITY_EDITOR
  181. if (string.IsNullOrEmpty(error))
  182. {
  183. switch (ws.InternalRequest.State)
  184. {
  185. // The request finished without any problem.
  186. case HTTPRequestStates.Finished:
  187. if (ws.InternalRequest.Response.IsSuccess || ws.InternalRequest.Response.StatusCode == 101)
  188. error = string.Format("Request finished. Status Code: {0} Message: {1}", ws.InternalRequest.Response.StatusCode.ToString(), ws.InternalRequest.Response.Message);
  189. else
  190. error = string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
  191. ws.InternalRequest.Response.StatusCode,
  192. ws.InternalRequest.Response.Message,
  193. ws.InternalRequest.Response.DataAsText);
  194. break;
  195. // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
  196. case HTTPRequestStates.Error:
  197. error = "Request Finished with Error! : " + ws.InternalRequest.Exception != null ? (ws.InternalRequest.Exception.Message + " " + ws.InternalRequest.Exception.StackTrace) : string.Empty;
  198. break;
  199. // The request aborted, initiated by the user.
  200. case HTTPRequestStates.Aborted:
  201. error = "Request Aborted!";
  202. break;
  203. // Connecting to the server is timed out.
  204. case HTTPRequestStates.ConnectionTimedOut:
  205. error = "Connection Timed Out!";
  206. break;
  207. // The request didn't finished in the given time.
  208. case HTTPRequestStates.TimedOut:
  209. error = "Processing the request Timed Out!";
  210. break;
  211. }
  212. }
  213. #endif
  214. if (Manager.UpgradingTransport != this)
  215. (Manager as IManager).OnTransportError(this, error);
  216. else
  217. Manager.UpgradingTransport = null;
  218. }
  219. /// <summary>
  220. /// WebSocket implementation OnClosed event handler.
  221. /// </summary>
  222. private void OnClosed(WebSocket ws, ushort code, string message)
  223. {
  224. if (ws != Implementation)
  225. return;
  226. HTTPManager.Logger.Information("WebSocketTransport", "OnClosed");
  227. Close();
  228. if (Manager.UpgradingTransport != this)
  229. (Manager as IManager).TryToReconnect();
  230. else
  231. Manager.UpgradingTransport = null;
  232. }
  233. #endregion
  234. #region Packet Sending Implementation
  235. /// <summary>
  236. /// A WebSocket implementation of the packet sending.
  237. /// </summary>
  238. public void Send(Packet packet)
  239. {
  240. if (State == TransportStates.Closed ||
  241. State == TransportStates.Paused)
  242. {
  243. HTTPManager.Logger.Information("WebSocketTransport", string.Format("Send - State == {0}, skipping packet sending!", State));
  244. return;
  245. }
  246. string encoded = packet.Encode();
  247. if (HTTPManager.Logger.Level <= BestHTTP.Logger.Loglevels.All)
  248. HTTPManager.Logger.Verbose("WebSocketTransport", "Send: " + encoded);
  249. if (packet.AttachmentCount != 0 || (packet.Attachments != null && packet.Attachments.Count != 0))
  250. {
  251. if (packet.Attachments == null)
  252. throw new ArgumentException("packet.Attachments are null!");
  253. if (packet.AttachmentCount != packet.Attachments.Count)
  254. throw new ArgumentException("packet.AttachmentCount != packet.Attachments.Count. Use the packet.AddAttachment function to add data to a packet!");
  255. }
  256. Implementation.Send(encoded);
  257. if (packet.AttachmentCount != 0)
  258. {
  259. int maxLength = packet.Attachments[0].Length + 1;
  260. for (int cv = 1; cv < packet.Attachments.Count; ++cv)
  261. if ((packet.Attachments[cv].Length + 1) > maxLength)
  262. maxLength = packet.Attachments[cv].Length + 1;
  263. if (Buffer == null || Buffer.Length < maxLength)
  264. Array.Resize(ref Buffer, maxLength);
  265. for (int i = 0; i < packet.AttachmentCount; i++)
  266. {
  267. Buffer[0] = (byte)TransportEventTypes.Message;
  268. Array.Copy(packet.Attachments[i], 0, Buffer, 1, packet.Attachments[i].Length);
  269. Implementation.Send(Buffer, 0, (ulong)packet.Attachments[i].Length + 1UL);
  270. }
  271. }
  272. }
  273. /// <summary>
  274. /// A WebSocket implementation of the packet sending.
  275. /// </summary>
  276. public void Send(List<Packet> packets)
  277. {
  278. for (int i = 0; i < packets.Count; ++i)
  279. Send(packets[i]);
  280. packets.Clear();
  281. }
  282. #endregion
  283. #region Packet Handling
  284. /// <summary>
  285. /// Will only process packets that need to upgrade. All other packets are passed to the Manager.
  286. /// </summary>
  287. private void OnPacket(Packet packet)
  288. {
  289. switch (packet.TransportEvent)
  290. {
  291. case TransportEventTypes.Open:
  292. if (this.State != TransportStates.Opening)
  293. HTTPManager.Logger.Warning("WebSocketTransport", "Received 'Open' packet while state is '" + State.ToString() + "'");
  294. else
  295. State = TransportStates.Open;
  296. goto default;
  297. case TransportEventTypes.Pong:
  298. // Answer for a Ping Probe.
  299. if (packet.Payload == "probe")
  300. {
  301. State = TransportStates.Open;
  302. (Manager as IManager).OnTransportProbed(this);
  303. }
  304. goto default;
  305. default:
  306. if (Manager.UpgradingTransport != this)
  307. (Manager as IManager).OnPacket(packet);
  308. break;
  309. }
  310. }
  311. #endregion
  312. }
  313. }
  314. #endif
  315. #endif