HandshakeData.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #if !BESTHTTP_DISABLE_SOCKETIO
  2. using System;
  3. using System.Collections.Generic;
  4. namespace BestHTTP.SocketIO
  5. {
  6. using BestHTTP.JSON;
  7. /// <summary>
  8. /// Helper class to parse and hold handshake information.
  9. /// </summary>
  10. public sealed class HandshakeData
  11. {
  12. #region Public Handshake Data
  13. /// <summary>
  14. /// Session ID of this connection.
  15. /// </summary>
  16. public string Sid { get; private set; }
  17. /// <summary>
  18. /// List of possible upgrades.
  19. /// </summary>
  20. public List<string> Upgrades { get; private set; }
  21. /// <summary>
  22. /// What interval we have to set a ping message.
  23. /// </summary>
  24. public TimeSpan PingInterval { get; private set; }
  25. /// <summary>
  26. /// What time have to pass without an answer to our ping request when we can consider the connection disconnected.
  27. /// </summary>
  28. public TimeSpan PingTimeout { get; private set; }
  29. #endregion
  30. #region Helper Methods
  31. public bool Parse(string str)
  32. {
  33. bool success = false;
  34. Dictionary<string, object> dict = Json.Decode(str, ref success) as Dictionary<string, object>;
  35. if (!success)
  36. return false;
  37. try
  38. {
  39. this.Sid = GetString(dict, "sid");
  40. this.Upgrades = GetStringList(dict, "upgrades");
  41. this.PingInterval = TimeSpan.FromMilliseconds(GetInt(dict, "pingInterval"));
  42. this.PingTimeout = TimeSpan.FromMilliseconds(GetInt(dict, "pingTimeout"));
  43. }
  44. catch (Exception ex)
  45. {
  46. BestHTTP.HTTPManager.Logger.Exception("HandshakeData", "Parse", ex);
  47. return false;
  48. }
  49. return true;
  50. }
  51. private static object Get(Dictionary<string, object> from, string key)
  52. {
  53. object value;
  54. if (!from.TryGetValue(key, out value))
  55. throw new System.Exception(string.Format("Can't get {0} from Handshake data!", key));
  56. return value;
  57. }
  58. private static string GetString(Dictionary<string, object> from, string key)
  59. {
  60. return Get(from, key) as string;
  61. }
  62. private static List<string> GetStringList(Dictionary<string, object> from, string key)
  63. {
  64. List<object> value = Get(from, key) as List<object>;
  65. List<string> result = new List<string>(value.Count);
  66. for (int i = 0; i < value.Count; ++i)
  67. {
  68. string str = value[i] as string;
  69. if (str != null)
  70. result.Add(str);
  71. }
  72. return result;
  73. }
  74. private static int GetInt(Dictionary<string, object> from, string key)
  75. {
  76. return (int)(double)Get(from, key);
  77. }
  78. #endregion
  79. }
  80. }
  81. #endif