fly 2 yıl önce
ebeveyn
işleme
9f1db67de0
2 değiştirilmiş dosya ile 74 ekleme ve 298 silme
  1. 73 297
      src/InteractionCenter/VinnoServerService.cs
  2. 1 1
      src/WingServer.cs

+ 73 - 297
src/InteractionCenter/VinnoServerService.cs

@@ -20,12 +20,10 @@ namespace WingCloudServer.InteractionCenter
     /// <summary>
     /// 最快服务器响应服务
     /// </summary>
-    public class VinnoServerService : InteractionCenterService, IVinnoServerService
+    public class VinnoServerService : JsonRpcService, IVinnoServerService
     {
         private IDistributedServerInfoDBService _distributedServerInfoDBService;
 
-        private string _fastServerHost = ConfigurationManager.GetParammeter<StringParameter>("FastServer", "ServerHost").Value;
-
         private HttpListener _listener = new HttpListener();
 
         private IAuthenticationService _authenticationService;
@@ -58,7 +56,7 @@ namespace WingCloudServer.InteractionCenter
         /// </summary>
         private IList<CacheDistributedServerInfosDTO> LoadServerInfosFormDbWithIds(IList<string> ids)
         {
-            
+
             var serverInformationList = GetServerInformationList(ids).Result;
             if (serverInformationList?.Count > 0)
             {
@@ -70,22 +68,25 @@ namespace WingCloudServer.InteractionCenter
         /// <summary>
         /// Get Server Information From DB
         /// </summary>
-        private async Task<IList<CacheDistributedServerInfosDTO>> GetServerInformationList(IList<string> ids) 
+        private async Task<IList<CacheDistributedServerInfosDTO>> GetServerInformationList(IList<string> ids)
         {
-            try 
+            try
             {
                 IList<CacheDistributedServerInfosDTO> serverInformationList = new List<CacheDistributedServerInfosDTO>();
-                if (_distributedServerInfoDBService == null) 
+                if (_distributedServerInfoDBService == null)
                 {
                     throw new Exception("MongoDB Init Error");
                 }
-                if (ids == null || ids.Count <= 0) {
-                    var request = new GetDistributedServerInfoDBPagesRequest(){
+                if (ids == null || ids.Count <= 0)
+                {
+                    var request = new GetDistributedServerInfoDBPagesRequest()
+                    {
                         CurrentPage = 1,
                         PageSize = 1000
                     };
                     var serverPageInfo = await _distributedServerInfoDBService.GetDistributedServerInfoPagesAsync(request);
-                    if (serverPageInfo != null && serverPageInfo.TotalCount > 0 && serverPageInfo.PageData != null && serverPageInfo.PageData.Any()) {
+                    if (serverPageInfo != null && serverPageInfo.TotalCount > 0 && serverPageInfo.PageData != null && serverPageInfo.PageData.Any())
+                    {
                         serverInformationList = serverPageInfo.PageData.Select(d => new CacheDistributedServerInfosDTO
                         {
                             Code = d.ServerCode,
@@ -98,13 +99,16 @@ namespace WingCloudServer.InteractionCenter
                         }).ToList();
                     }
                 }
-                else {
+                else
+                {
                     //根据id查询
-                    var request = new GetDistributedServerInfoDBByCodesRequest() {
+                    var request = new GetDistributedServerInfoDBByCodesRequest()
+                    {
                         Codes = ids.ToList()
                     };
                     var serverPageInfo = await _distributedServerInfoDBService.GetDistributedServerInfoDBByCodesAsync(request);
-                    if (serverPageInfo != null && serverPageInfo.Any()) {
+                    if (serverPageInfo != null && serverPageInfo.Any())
+                    {
                         serverInformationList = serverPageInfo.Select(d => new CacheDistributedServerInfosDTO
                         {
                             Code = d.ServerCode,
@@ -119,7 +123,7 @@ namespace WingCloudServer.InteractionCenter
                 }
                 return serverInformationList;
             }
-            catch (Exception ex) 
+            catch (Exception ex)
             {
                 throw ex;
             }
@@ -131,11 +135,10 @@ namespace WingCloudServer.InteractionCenter
         public override void Load(JsonRpcClientPool jsonRpcClientPool)
         {
             base.Load(jsonRpcClientPool);
-            _distributedServerInfoDBService = GetProxy<IDistributedServerInfoDBService>();       
-            _authenticationService = GetProxy<IAuthenticationService>();  
-            _tokenDBService = GetProxy<ITokenDBService>();  
-            LoadDBServerInfo();   
-            InitVinnoServerService(_fastServerHost);           
+            _distributedServerInfoDBService = GetProxy<IDistributedServerInfoDBService>();
+            _authenticationService = GetProxy<IAuthenticationService>();
+            _tokenDBService = GetProxy<ITokenDBService>();
+            LoadDBServerInfo();
         }
 
         /// <summary>
@@ -148,30 +151,30 @@ namespace WingCloudServer.InteractionCenter
            {
                try
                {
-                    int tryCount = 1;
-                    IList<CacheDistributedServerInfosDTO> serverInformationList = null;
-                    while (true) 
-                    {
-                        try 
-                        {
-                            serverInformationList = await GetServerInformationList(null);
-                        }
-                        catch (Exception ex) 
-                        {
-                            Logger.WriteLineError($"ServerInfo Cache Init Error:{ex}");
-                        }
-                        if (serverInformationList != null) 
-                        {
-                            break;
-                        }
-                        tryCount++;
-                        if (tryCount > 10) 
-                        {
-                            break;
-                        }
-                        await Task.Delay(500);
-                    }
-                    CacheMaintenance.Instance.Get<IDistributedServerInfosManager>().LoadFromDbOject(serverInformationList);
+                   int tryCount = 1;
+                   IList<CacheDistributedServerInfosDTO> serverInformationList = null;
+                   while (true)
+                   {
+                       try
+                       {
+                           serverInformationList = await GetServerInformationList(null);
+                       }
+                       catch (Exception ex)
+                       {
+                           Logger.WriteLineError($"ServerInfo Cache Init Error:{ex}");
+                       }
+                       if (serverInformationList != null)
+                       {
+                           break;
+                       }
+                       tryCount++;
+                       if (tryCount > 10)
+                       {
+                           break;
+                       }
+                       await Task.Delay(500);
+                   }
+                   CacheMaintenance.Instance.Get<IDistributedServerInfosManager>().LoadFromDbOject(serverInformationList);
                }
                catch (Exception ex)
                {
@@ -180,302 +183,75 @@ namespace WingCloudServer.InteractionCenter
            });
         }
 
-        #region 监听服务
-
-        /// <summary>
-        /// 初始化监听
-        /// </summary>
-        private void InitVinnoServerService(string fastServerHost = "http://*:9304/")
-        {   
-            //添加已经挂在的静态服务的监听
-            _listener.Prefixes.Add(fastServerHost);
-            //启动监听器
-            _listener.Start();
-            //异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
-            //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
-            _listener.BeginGetContext(Result, null);
-        }
-
-        /// <summary>
-        /// 接收请求委托
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        private void Result(IAsyncResult ar)
-        {
-            //继续异步监听
-            _listener.BeginGetContext(Result, null);
-            //获得context对象
-            var context = _listener.EndGetContext(ar);
-            HandleHttpContext(context);
-        }
-
-        /// <summary>
-        /// 最快服务监听
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        /// <returns>输出文件流</returns>
-        private async void HandleHttpContext(HttpListenerContext context)
-        {
-            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
-            if (context.Request.HttpMethod == "OPTIONS")
-            { 
-                JsonPResponse(context);
-            }
-            else
-            {
-                if (context.Request.HttpMethod == "GET")
-                {
-                    GetMethodResponse(context);
-                }
-                else
-                {
-                    ResponseContent(context, false);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Get请求
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        /// <returns>输出文件流</returns>
-        private async void GetMethodResponse(HttpListenerContext context)
-        {
-            try
-            {
-                //读地址
-                var uri = context.Request.Url;
-                if (uri != null)
-                {
-                    var absPath = uri.AbsolutePath;                        
-                    //拦截,处理doc文档
-                    if (absPath.Contains("EchoRequest"))
-                    {
-                        var echoResult = new EchoResult();
-                        ResponseContent(context, true, echoResult);
-                        return;
-                    }
-                    else if (absPath.Contains("LoginSuccessRequest"))
-                    {
-                        await LoginSuccess(context);
-                        return;
-                    }
-                    else if (absPath.Contains("ServerListRequest"))
-                    {
-                        var req = new QueryServerInfoRequest()
-                        {
-                            Codes = new List<string>()
-                        };
-                        var model = new ServerListResult()
-                        {
-                            IsDistributed = ConfigurationManager.IsDistributed,
-                            ServerList = await GetServerInfoListAsync(req)
-                        };
-                        ResponseContent(context, true, model);
-                        return;
-                    }
-                }                    
-                ResponseContent(context, false);
-            }
-            catch(Exception ex)
-            {
-                Logger.WriteLineError($"GetError:{ex}");
-                ResponseContent(context, false);
-            }
-        }
-
-        /// <summary>
-        /// 登录成功Get请求
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        private async Task<bool> LoginSuccess(HttpListenerContext context) 
-        {
-            var requestToken = "";
-            if (context.Request.Headers.Count > 0) {
-                try 
-                {
-                    requestToken = context.Request.Headers?.GetValues("Token")?.ToList()?.FirstOrDefault() ?? string.Empty;
-                }
-                catch (Exception ex) 
-                {
-                    Logger.WriteLineError($"GetHeadersError:{ex}");
-                    ResponseContent(context, false);
-                    return true;
-                }
-            }
-            string requestIp = null;
-            if (context.Request.RemoteEndPoint != null)
-            {
-                requestIp = context.Request.RemoteEndPoint.Address.ToString();
-            }
-            var tokenInfo = await ValidateTokenAsync(requestToken);
-            if (tokenInfo != null) 
-            {
-                tokenInfo.IpValue = IpToLong(requestIp);
-                var res = await _tokenDBService.UpdateTokenAsync(tokenInfo.Code, tokenInfo);
-                if (res) 
-                {
-                    CacheMaintenance.Instance.Get<IDistributedServerInfosManager>().Remove(tokenInfo.Code);
-                    var response = new LoginSuccessResult();
-                    ResponseContent(context, true, response);
-                    return true;
-                }
-            }
-            ResponseContent(context, false);
-            return false;
-        }
-
-        /// <summary>
-        /// ip地址转long
-        /// </summary>
-        /// <param name="ipAddress"></param>
-        /// <returns></returns>
-        private long IpToLong(string ipAddress)
-        {
-            byte[] byts = IPAddress.Parse(ipAddress).GetAddressBytes();
-            Array.Reverse(byts); // 需要倒置一次字节序
-            long ipLong = BitConverter.ToUInt32(byts, 0);
-            return ipLong;
-        }
-
-        /// <summary>
-        /// 时间转长整形的时间戳
-        /// </summary>
-        /// <returns>""</returns>
-        private async Task<TokenDTO> ValidateTokenAsync(string token)
-        {
-            var request = new WingInterfaceLibrary.Request.Authentication.ValidateTokenRequest() { Token = token };
-            var result = await _authenticationService.ValidateTokenAsync(request);
-            //Check 权限
-            if (result != null && result.Code != WingInterfaceLibrary.Enum.CustomerRpcCode.Ok)
-            {
-                return null;
-            }
-            return result.Token; 
-        }
-
-        /// <summary>
-        /// 跨域访问
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        /// <returns>输出文件流</returns>
-        private async void JsonPResponse(HttpListenerContext context)
-        {
-            try
-            {
-                //后台跨域请求,必须配置
-                context.Response.AppendHeader("Access-Control-Allow-Headers", "*");
-                context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
-                context.Response.AddHeader("Access-Control-Max-Age", "1800");
-                context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
-                var resp = new BaseServerResult();
-                ResponseContent(context, true, resp);
-            }
-            catch(Exception ex)
-            {
-                Logger.WriteLineError($"OPTIONSError:{ex}");
-                ResponseContent(context, false);
-            }
-        }
-
-        /// <summary>
-        /// 输出结果
-        /// </summary>
-        /// <param name="context">监听到的上下问对象</param>
-        /// <param name="isSuccess">是否成功:true </param>
-        /// <param name="code">错误码</param>
-        /// <param name="msg">内容</param>
-        /// <returns>输出结果</returns>
-        private void ResponseContent(HttpListenerContext context, bool isSuccess = false, object data = null)
-        {
-            try
-            {
-                if (data == null) 
-                {
-                    data = new BaseServerResult() 
-                    { 
-                        Code = 1 
-                    };
-                }
-                var str = JsonConvert.SerializeObject(data);
-                context.Response.ContentType = "application/json";
-                if (isSuccess) 
-                {
-                    context.Response.StatusCode = (int)HttpStatusCode.OK;
-                    context.Response.StatusDescription = "OK";
-                }
-                byte[] bytesR = System.Text.Encoding.UTF8.GetBytes(str);
-                context.Response.ContentLength64 = bytesR.Length;
-                context.Response.OutputStream.Write(bytesR, 0, bytesR.Length);
-                //输出结束并关闭流                               
-                context.Response.OutputStream.Flush();
-                context.Response.OutputStream.Close();
-            }
-            catch(Exception ex)
-            {
-                Logger.WriteLineError($"ResponseContent Error:{ex}");
-            }
-        }
-        #endregion 
-
         /// <summary>
         /// Get op logs from master server
         /// </summary>
         /// <param name="request"></param>
         /// <returns>The op log list</returns>
         public async Task<bool> UpdateServerInfoAsync(UpdateServerInfoRequest request)
-        {            
+        {
             //这里应该是批量移除,请求参数要改
-            if (request.Codes != null && request.Codes.Any()) 
+            if (request.Codes != null && request.Codes.Any())
             {
-                foreach (var code in request.Codes) 
+                foreach (var code in request.Codes)
                 {
                     CacheMaintenance.Instance.Get<IDistributedServerInfosManager>().Remove(code);
                 }
-                return true;
+                return await Task.FromResult(true);
             }
-            else {
+            else
+            {
                 LoadDBServerInfo();
             }
-            return false;
-        }     
+            return await Task.FromResult(false);
+        }
 
         /// <summary>
-        /// Synchronize op log to master server
+        /// 最快服务器列表
         /// </summary>
         /// <param name="request"></param>
         /// <returns></returns>
         public async Task<List<ServerInfoDTO>> GetServerInfoListAsync(QueryServerInfoRequest request)
-        {            
+        {
             //这里应该是批量查询,请求参数要改
             var list = new List<ServerInfoDTO>();
             var serverInformationList = new List<CacheDistributedServerInfosDTO>();
-            if (request.Codes != null  && request.Codes.Any()) 
+            if (request.Codes != null && request.Codes.Any())
             {
                 foreach (var item in request.Codes)
                 {
                     var entity = CacheMaintenance.Instance.Get<IDistributedServerInfosManager>().Get(item);
-                    if (entity != null && !string.IsNullOrEmpty(entity.Code)) 
+                    if (entity != null && !string.IsNullOrEmpty(entity.Code))
                     {
                         serverInformationList.Add(entity);
                     }
                 }
-                
+
             }
             else
             {
                 serverInformationList = CacheMaintenance.Instance.Get<IDistributedServerInfosManager>()
                 .Where(x => !string.IsNullOrEmpty(x.Name) && !string.IsNullOrEmpty(x.ServerUrl))?.ToList();
             }
-            if (serverInformationList != null && serverInformationList.Any()) 
+            if (serverInformationList != null && serverInformationList.Any())
             {
-                list = serverInformationList.Select(c => new ServerInfoDTO() 
+                list = serverInformationList.Select(c => new ServerInfoDTO()
                 {
                     Name = c.Name,
                     Host = c.ServerUrl
                 }).ToList();
             }
-            return list;
-        }           
+            return await Task.FromResult(list);
+        }
+
+        /// <summary>
+        /// 测速接口 
+        /// </summary>
+        /// <returns></returns>
+        public async Task<EchoResult> EchoAsync()
+        {
+            var echoResult = new EchoResult();
+            return await Task.FromResult(echoResult);
+        }
     }
 }

+ 1 - 1
src/WingServer.cs

@@ -156,7 +156,7 @@ namespace WingCloudServer
                     //TODO
                 }
             }
-
+            //最快服务器
             var vinnoServerService = new VinnoServerService();
             _rpcHttpServer.RegisterService(typeof(WingInterfaceLibrary.Interface.IVinnoServerService), vinnoServerService);
             vinnoServerService.Load(rpcClientPool);