123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286 |
- using Newtonsoft.Json;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Net.Http;
- using System.Net.NetworkInformation;
- using System.Threading;
- using System.Threading.Tasks;
- using Vinno.IUS.Common.Log;
- namespace Vinno.vCloud.Common.FIS
- {
- public class vCloudTerminalBuilder
- {
- /// <summary>
- /// connect default server before get terminal connection faster address info from address info list
- /// if get null ,can not connected to internet
- /// </summary>
- /// <returns></returns>
- public static ServerInfo GetFasterServer(string filePath = null)
- {
- try
- {
- string settingFilePath = AppDomain.CurrentDomain.BaseDirectory;
- if (string.IsNullOrEmpty(settingFilePath))
- {
- if (!string.IsNullOrEmpty(filePath))
- {
- settingFilePath = filePath;
- }
- else
- {
- return null;
- }
- }
- ServerInfo fasterServer = null;
- var speedResults = new ConcurrentDictionary<ServerInfo, int>();
- var serverFilePath = Path.Combine(settingFilePath, "FISServerSettings.conf");
- DefaultServerSettings serverSettings = null;
- if (File.Exists(serverFilePath))
- {
- var stringValue = File.ReadAllText(serverFilePath);
- serverSettings = JsonConvert.DeserializeObject<DefaultServerSettings>(stringValue);
- }
- if (serverSettings == null)
- {
- serverSettings = new DefaultServerSettings
- {
- Servers = new List<ServerInfo>
- {
- new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 },
- new ServerInfo { Host = "cloud.flyinsono.com", Port = 9096 },
- new ServerInfo { Host = "cloud.xinglinghui.com", Port = 9096 },
- },
- MasterServer = new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 }
- };
- }
- Parallel.ForEach(serverSettings.Servers, serverInfo =>
- {
- var speed = GetConnectServerSpeed(serverInfo.Host);
- if (speed != -1)
- {
- speedResults.TryAdd(serverInfo, speed);
- }
- });
- if (speedResults.Count == 0)
- {
- fasterServer = serverSettings.MasterServer;
- }
- else
- {
- foreach (var result in speedResults)
- {
- if (fasterServer == null)
- {
- fasterServer = result.Key;
- }
- else
- {
- if (fasterServer.Host == "cloud.xinglinghui.com" && speedResults[fasterServer] > result.Value + 5)
- {
- fasterServer = result.Key;
- }
- else if (result.Key.Host == "cloud.xinglinghui.com" && speedResults[fasterServer] > result.Value - 5)
- {
- fasterServer = result.Key;
- }
- else if (speedResults[fasterServer] > result.Value)
- {
- fasterServer = result.Key;
- }
- }
- }
- }
- Logger.WriteLineInfo($"Get faster server is {fasterServer.Host}:{fasterServer.Port}");
- return fasterServer;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Get faster server error: {ex}");
- }
- return new ServerInfo { Host = "s01.flyinsono.com", Port = 9096 };
- }
- /// <summary>
- /// Connect to server
- /// </summary>
- /// <param name="connectionInfo">The connection Info</param>
- /// <returns></returns>
- public IvCloudTerminal Connect(ConnectionInfo connectionInfo, bool isUseOldTerminalSdk = false, string uniqueId = "", string terminalId = "")
- {
- if (string.IsNullOrEmpty(connectionInfo?.Account?.Name) || string.IsNullOrEmpty(connectionInfo?.Account?.Password))
- {
- return null;
- }
- var terminal = new vCloudTerminal(connectionInfo, isUseOldTerminalSdk);
- try
- {
- terminal.Connect(uniqueId, terminalId);
- }
- catch (Exception e)
- {
- Logger.WriteLineError($"Termnial Login ex:{e}");
- }
- return terminal;
- }
- /// <summary>
- /// Register Account
- /// </summary>
- /// <param name="connectionInfo"></param>
- /// <returns></returns>
- public bool Register(ConnectionInfo connectionInfo)
- {
- if (string.IsNullOrEmpty(connectionInfo?.Account?.Name) || string.IsNullOrEmpty(connectionInfo?.Account?.Password) || string.IsNullOrEmpty(connectionInfo?.Organization))
- {
- return false;
- }
- var terminal = new vCloudTerminal(connectionInfo);
- try
- {
- var result = terminal.Register();
- terminal.Dispose();
- return result;
- }
- catch (Exception e)
- {
- Logger.WriteLineError($"Termnial Register error, ex:{e}");
- }
- return false;
- }
- /// <summary>
- /// test connet server speed
- /// </summary>
- /// <param name="serverUrl"></param>
- /// <returns></returns>
- private static int GetConnectServerSpeed(string serverUrl)
- {
- try
- {
- using (var ping = new Ping())
- {
- var successTimes = 0;
- var totalTime = 0;
- for (var i = 0; i < 4; i++)//第一次为预热
- {
- try
- {
- var reply = ping.Send(serverUrl, 3000);
- if (reply.Status == IPStatus.Success && i > 0)
- {
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl}, spend time:{reply.RoundtripTime}ms");
- totalTime += (int)reply.RoundtripTime;
- successTimes++;
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Connect serverUrl:{serverUrl} error, Exception:{ex}");
- continue;
- }
- }
- if (successTimes == 0)
- {
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl} fail, the success times is 0");
- return -1;
- }
- else
- {
- var averageValue = totalTime / successTimes;
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl},successTimes:{successTimes},spend time averageValue:{averageValue}ms");
- return averageValue;
- }
- }
- }
- catch (Exception e)
- {
- Logger.WriteLineError($"Connect Server:{serverUrl}, SpeedTest exception:{e}");
- return -1;
- }
- }
- /// <summary>
- /// test connet server speed
- /// </summary>
- /// <param name="serverUrl"></param>
- /// <returns></returns>
- private static int Old_GetConnectServerSpeed(string serverUrl, bool isUseHttps = false)
- {
- try
- {
- //The following two lines are used to avoid HTTPS security authentication, otherwise httpclient cannot access the unsafe link
- var httpClientHandler = new HttpClientHandler
- {
- ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
- };
- using (var httpClient = new HttpClient(httpClientHandler))
- {
- var stopWatch = new Stopwatch();
- httpClient.Timeout = TimeSpan.FromSeconds(3);
- var prefix = "http://";
- if (isUseHttps)
- {
- prefix = "https://";
- }
- var successTimes = 0;
- var totalTime = 0;
- for (var i = 0; i < 4; i++)//第一次为预热
- {
- if (i > 0)
- {
- ////TODO(FISJuly): removed?
- Thread.Sleep(1000);
- }
- stopWatch.Restart();
- try
- {
- var result = httpClient.GetAsync(prefix + serverUrl + "/HomePage/API/Connect.json").GetAwaiter().GetResult();
- if (result != null)
- {
- var content = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
- stopWatch.Stop();
- if (result.IsSuccessStatusCode && content.Length > 0 && i > 0)
- {
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl}, spend time:{stopWatch.ElapsedMilliseconds}ms");
- totalTime += (int)stopWatch.ElapsedMilliseconds;
- successTimes++;
- }
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"Connect serverUrl:{serverUrl} error, Exception:{ex}");
- continue;
- }
- }
- if (successTimes == 0)
- {
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl} fail, the success times is 0");
- return -1;
- }
- else
- {
- var averageValue = totalTime / successTimes;
- Logger.WriteLineInfo($"Connect serverUrl:{serverUrl},successTimes:{successTimes},spend time averageValue:{averageValue}ms");
- return averageValue;
- }
- }
- }
- catch (Exception e)
- {
- Logger.WriteLineError($"Connect Server:{serverUrl}, SpeedTest exception:{e}");
- return -1;
- }
- }
- }
- }
|