WebSocketTransport.cs 14 KB

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