vCloudTerminalBuilder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Net.Http;
  8. using System.Net.NetworkInformation;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Vinno.IUS.Common.Log;
  12. namespace Vinno.vCloud.Common.FIS
  13. {
  14. public class vCloudTerminalBuilder
  15. {
  16. /// <summary>
  17. /// connect default server before get terminal connection faster address info from address info list
  18. /// if get null ,can not connected to internet
  19. /// </summary>
  20. /// <returns></returns>
  21. public static ServerInfo GetFasterServer(string filePath = null)
  22. {
  23. try
  24. {
  25. string settingFilePath = AppDomain.CurrentDomain.BaseDirectory;
  26. if (string.IsNullOrEmpty(settingFilePath))
  27. {
  28. if (!string.IsNullOrEmpty(filePath))
  29. {
  30. settingFilePath = filePath;
  31. }
  32. else
  33. {
  34. return null;
  35. }
  36. }
  37. ServerInfo fasterServer = null;
  38. var speedResults = new ConcurrentDictionary<ServerInfo, int>();
  39. var serverFilePath = Path.Combine(settingFilePath, "FISServerSettings.conf");
  40. DefaultServerSettings serverSettings = null;
  41. if (File.Exists(serverFilePath))
  42. {
  43. var stringValue = File.ReadAllText(serverFilePath);
  44. serverSettings = JsonConvert.DeserializeObject<DefaultServerSettings>(stringValue);
  45. }
  46. if (serverSettings == null)
  47. {
  48. serverSettings = new DefaultServerSettings
  49. {
  50. Servers = new List<ServerInfo>
  51. {
  52. new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 },
  53. new ServerInfo { Host = "cloud.flyinsono.com", Port = 9096 },
  54. new ServerInfo { Host = "cloud.xinglinghui.com", Port = 9096 },
  55. },
  56. MasterServer = new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 }
  57. };
  58. }
  59. Parallel.ForEach(serverSettings.Servers, serverInfo =>
  60. {
  61. var speed = GetConnectServerSpeed(serverInfo.Host);
  62. if (speed != -1)
  63. {
  64. speedResults.TryAdd(serverInfo, speed);
  65. }
  66. });
  67. if (speedResults.Count == 0)
  68. {
  69. fasterServer = serverSettings.MasterServer;
  70. }
  71. else
  72. {
  73. foreach (var result in speedResults)
  74. {
  75. if (fasterServer == null)
  76. {
  77. fasterServer = result.Key;
  78. }
  79. else
  80. {
  81. if (fasterServer.Host == "cloud.xinglinghui.com" && speedResults[fasterServer] > result.Value + 5)
  82. {
  83. fasterServer = result.Key;
  84. }
  85. else if (result.Key.Host == "cloud.xinglinghui.com" && speedResults[fasterServer] > result.Value - 5)
  86. {
  87. fasterServer = result.Key;
  88. }
  89. else if (speedResults[fasterServer] > result.Value)
  90. {
  91. fasterServer = result.Key;
  92. }
  93. }
  94. }
  95. }
  96. Logger.WriteLineInfo($"Get faster server is {fasterServer.Host}:{fasterServer.Port}");
  97. return fasterServer;
  98. }
  99. catch (Exception ex)
  100. {
  101. Logger.WriteLineError($"Get faster server error: {ex}");
  102. }
  103. return new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 };
  104. }
  105. /// <summary>
  106. /// Connect to server
  107. /// </summary>
  108. /// <param name="connectionInfo">The connection Info</param>
  109. /// <returns></returns>
  110. public IvCloudTerminal Connect(ConnectionInfo connectionInfo, bool isUseOldTerminalSdk = false, string uniqueId = "", string terminalId = "")
  111. {
  112. if (string.IsNullOrEmpty(connectionInfo?.Account?.Name) || string.IsNullOrEmpty(connectionInfo?.Account?.Password))
  113. {
  114. return null;
  115. }
  116. var terminal = new vCloudTerminal(connectionInfo, isUseOldTerminalSdk);
  117. try
  118. {
  119. terminal.Connect(uniqueId, terminalId);
  120. }
  121. catch (Exception e)
  122. {
  123. Logger.WriteLineError($"Termnial Login ex:{e}");
  124. }
  125. return terminal;
  126. }
  127. /// <summary>
  128. /// Register Account
  129. /// </summary>
  130. /// <param name="connectionInfo"></param>
  131. /// <returns></returns>
  132. public bool Register(ConnectionInfo connectionInfo)
  133. {
  134. if (string.IsNullOrEmpty(connectionInfo?.Account?.Name) || string.IsNullOrEmpty(connectionInfo?.Account?.Password) || string.IsNullOrEmpty(connectionInfo?.Organization))
  135. {
  136. return false;
  137. }
  138. var terminal = new vCloudTerminal(connectionInfo);
  139. try
  140. {
  141. var result = terminal.Register();
  142. terminal.Dispose();
  143. return result;
  144. }
  145. catch (Exception e)
  146. {
  147. Logger.WriteLineError($"Termnial Register error, ex:{e}");
  148. }
  149. return false;
  150. }
  151. /// <summary>
  152. /// test connet server speed
  153. /// </summary>
  154. /// <param name="serverUrl"></param>
  155. /// <returns></returns>
  156. private static int GetConnectServerSpeed(string serverUrl)
  157. {
  158. try
  159. {
  160. using (var ping = new Ping())
  161. {
  162. var successTimes = 0;
  163. var totalTime = 0;
  164. for (var i = 0; i < 4; i++)//第一次为预热
  165. {
  166. try
  167. {
  168. var reply = ping.Send(serverUrl, 3000);
  169. if (reply.Status == IPStatus.Success && i > 0)
  170. {
  171. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl}, spend time:{reply.RoundtripTime}ms");
  172. totalTime += (int)reply.RoundtripTime;
  173. successTimes++;
  174. }
  175. }
  176. catch (Exception ex)
  177. {
  178. Logger.WriteLineError($"Connect serverUrl:{serverUrl} error, Exception:{ex}");
  179. continue;
  180. }
  181. }
  182. if (successTimes == 0)
  183. {
  184. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl} fail, the success times is 0");
  185. return -1;
  186. }
  187. else
  188. {
  189. var averageValue = totalTime / successTimes;
  190. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl},successTimes:{successTimes},spend time averageValue:{averageValue}ms");
  191. return averageValue;
  192. }
  193. }
  194. }
  195. catch (Exception e)
  196. {
  197. Logger.WriteLineError($"Connect Server:{serverUrl}, SpeedTest exception:{e}");
  198. return -1;
  199. }
  200. }
  201. /// <summary>
  202. /// test connet server speed
  203. /// </summary>
  204. /// <param name="serverUrl"></param>
  205. /// <returns></returns>
  206. private static int Old_GetConnectServerSpeed(string serverUrl, bool isUseHttps = false)
  207. {
  208. try
  209. {
  210. //The following two lines are used to avoid HTTPS security authentication, otherwise httpclient cannot access the unsafe link
  211. var httpClientHandler = new HttpClientHandler
  212. {
  213. ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
  214. };
  215. using (var httpClient = new HttpClient(httpClientHandler))
  216. {
  217. var stopWatch = new Stopwatch();
  218. httpClient.Timeout = TimeSpan.FromSeconds(3);
  219. var prefix = "http://";
  220. if (isUseHttps)
  221. {
  222. prefix = "https://";
  223. }
  224. var successTimes = 0;
  225. var totalTime = 0;
  226. for (var i = 0; i < 4; i++)//第一次为预热
  227. {
  228. if (i > 0)
  229. {
  230. ////TODO(FISJuly): removed?
  231. Thread.Sleep(1000);
  232. }
  233. stopWatch.Restart();
  234. try
  235. {
  236. var result = httpClient.GetAsync(prefix + serverUrl + "/HomePage/API/Connect.json").GetAwaiter().GetResult();
  237. if (result != null)
  238. {
  239. var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
  240. stopWatch.Stop();
  241. if (result.IsSuccessStatusCode && content.Length > 0 && i > 0)
  242. {
  243. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl}, spend time:{stopWatch.ElapsedMilliseconds}ms");
  244. totalTime += (int)stopWatch.ElapsedMilliseconds;
  245. successTimes++;
  246. }
  247. }
  248. }
  249. catch (Exception ex)
  250. {
  251. Logger.WriteLineError($"Connect serverUrl:{serverUrl} error, Exception:{ex}");
  252. continue;
  253. }
  254. }
  255. if (successTimes == 0)
  256. {
  257. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl} fail, the success times is 0");
  258. return -1;
  259. }
  260. else
  261. {
  262. var averageValue = totalTime / successTimes;
  263. Logger.WriteLineInfo($"Connect serverUrl:{serverUrl},successTimes:{successTimes},spend time averageValue:{averageValue}ms");
  264. return averageValue;
  265. }
  266. }
  267. }
  268. catch (Exception e)
  269. {
  270. Logger.WriteLineError($"Connect Server:{serverUrl}, SpeedTest exception:{e}");
  271. return -1;
  272. }
  273. }
  274. }
  275. }