WebSocketTransport.cs 13 KB

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