denny 2 жил өмнө
parent
commit
94a59e8b35

+ 101 - 71
src/InteractionCenter/FastestServerInteractionCenterService.cs

@@ -94,23 +94,41 @@ namespace WingCloudServer.InteractionCenter
         {   
             //添加已经挂在的静态服务的监听
             _listener.Prefixes.Add(fastServerHost);
+            //启动监听器
             _listener.Start();
-            Task.Run(async () =>
-            {
-                while (true)
-                {
-                    try
-                    {
-                        var context = await _listener.GetContextAsync().ConfigureAwait(false);
-                        HandleHttpContext(context);
-                    }
-                    catch (Exception ex)
-                    {
-                        Logger.WriteLineError($"ListenFastestServerError:{ex}");
-                    }
-                }
-            });
+            //异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
+            //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
+            _listener.BeginGetContext(Result, null);
+            // Task.Run(async () =>
+            // {
+            //     while (true)
+            //     {
+            //         try
+            //         {
+            //             var context = await _listener.GetContextAsync().ConfigureAwait(false);
+            //             HandleHttpContext(context);
+            //         }
+            //         catch (Exception ex)
+            //         {
+            //             Logger.WriteLineError($"ListenFastestServerError:{ex}");
+            //         }
+            //     }
+            // });
         }
+
+        /// <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>
@@ -125,12 +143,6 @@ namespace WingCloudServer.InteractionCenter
             }
             else
             {
-                var requestContent = new 
-                {
-                    RequestUrl = context.Request?.Url?.AbsoluteUri,
-                    Authorization = context.Request?.Headers?["Authorization"],
-                    HttpMethod = context.Request?.HttpMethod
-                };
                 if (context.Request.HttpMethod == "GET")
                 {
                     GetMethodResponse(context);
@@ -157,17 +169,17 @@ namespace WingCloudServer.InteractionCenter
                 {
                     var absPath = uri.AbsolutePath;                        
                     //拦截,处理doc文档
-                    if (absPath.Contains("GetConnectSpeed"))
+                    if (absPath.Contains("Echo"))
                     {
                         ResponseContent(context, true, JsonConvert.SerializeObject(new FastestServerBaseDTO() { Code = 1 }));
                         return;
                     }
-                    else if (absPath.Contains("SendConnectMessage"))
+                    else if (absPath.Contains("LoginSuccess"))
                     {
                         LoginSuccess(context);
                         return;
                     }
-                    else if (absPath.Contains("GetServerConfig"))
+                    else if (absPath.Contains("GetServerList"))
                     {
                         var model = new FastestServerDTO()
                         {
@@ -197,10 +209,12 @@ namespace WingCloudServer.InteractionCenter
         {
             var requestToken = "";
             if (context.Request.Headers.Count > 0) {
-                try {
+                try 
+                {
                     requestToken = context.Request.Headers?.GetValues("Token")?.ToList()?.FirstOrDefault();
                 }
-                catch (Exception ex) {
+                catch (Exception ex) 
+                {
                     Logger.WriteLineError($"GetHeadersError:{ex}");
                     ResponseContent(context, false, JsonConvert.SerializeObject(new FastestServerBaseDTO() { Code = 0 }));
                     return;
@@ -216,7 +230,8 @@ namespace WingCloudServer.InteractionCenter
             {
                 tokenInfo.IpValue = IpToLong(requestIp);
                 var res = await _tokenDBService.UpdateTokenAsync(tokenInfo.Code, tokenInfo);
-                if (res) {
+                if (res) 
+                {
                     _fastestServerManager.Remove(tokenInfo.Code);
                     ResponseContent(context, true, JsonConvert.SerializeObject(new FastestServerBaseDTO() { Code = 1 }));
                     return;
@@ -253,20 +268,6 @@ namespace WingCloudServer.InteractionCenter
             return result.Token; 
         }
 
-        /// <summary>
-        /// 时间转长整形的时间戳
-        /// </summary>
-        /// <param name="time">当前时间</param>
-        /// <param name="isUtc">是否utc格式时间戳</param>
-        /// <returns>true</returns>
-        private async Task<long> ToTimestamp(DateTime time, bool isUtc = false)
-        {
-            DateTime refTime = TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1970, 1, 1), TimeZoneInfo.Utc);
-            var diffSpan = (isUtc ? time : time.ToUniversalTime()) - refTime;
-            long unixTime = (long)Math.Round(diffSpan.TotalMilliseconds, MidpointRounding.AwayFromZero);
-            return unixTime;
-        }
-
         /// <summary>
         /// 跨域访问
         /// </summary>
@@ -334,9 +335,25 @@ namespace WingCloudServer.InteractionCenter
            {
                try
                {
-                   await Task.Delay(5000);
-                   var serverInformationList = await GetServerInformationList(null);
-                   _fastestServerManager.LoadFromDbOject(serverInformationList);
+                    //await Task.Delay(5000);
+                    IList<ServerInformation> serverInformationList = null;
+                    while (true) 
+                    {
+                        try 
+                        {
+                            serverInformationList = await GetServerInformationList(null);
+                        }
+                        catch (Exception ex) 
+                        {
+                            Logger.WriteLineError($"ServerInfo Cache Init Error:{ex}");
+                        }
+                        if (serverInformationList != null) 
+                        {
+                            break;
+                        }
+                        await Task.Delay(500);
+                    }
+                    _fastestServerManager.LoadFromDbOject(serverInformationList);
                }
                catch (Exception ex)
                {
@@ -350,36 +367,49 @@ namespace WingCloudServer.InteractionCenter
         /// </summary>
         private async Task<IList<ServerInformation>> GetServerInformationList(IList<string> ids) 
         {
-            IList<ServerInformation> serverInformationList = new List<ServerInformation>();
-            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()) {
-                    serverInformationList = serverPageInfo.PageData.Select(d => new ServerInformation{
-                        Code = d.ServerCode,
-                        Name = d.Name,
-                        Host = d.ServerUrl
-                    }).ToList();
+            try 
+            {
+                IList<ServerInformation> serverInformationList = new List<ServerInformation>();
+                if (_distributedServerInfoDBService == null) 
+                {
+                    throw new Exception("MongoDB Init Error");
                 }
-            }
-            else {
-                //根据id查询
-                var request = new GetDistributedServerInfoDBByCodesRequest() {
-                    Codes = ids.ToList()
-                };
-                var serverPageInfo = await _distributedServerInfoDBService.GetDistributedServerInfoDBByCodesAsync(request);
-                if (serverPageInfo != null && serverPageInfo.Any()) {
-                    serverInformationList = serverPageInfo.Select(d => new ServerInformation{
-                        Code = d.ServerCode,
-                        Name = d.Name,
-                        Host = d.ServerUrl
-                    }).ToList();
+                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()) {
+                        serverInformationList = serverPageInfo.PageData.Select(d => new ServerInformation
+                        {
+                            Code = d.ServerCode,
+                            Name = d.Name,
+                            Host = d.ServerUrl
+                        }).ToList();
+                    }
+                }
+                else {
+                    //根据id查询
+                    var request = new GetDistributedServerInfoDBByCodesRequest() {
+                        Codes = ids.ToList()
+                    };
+                    var serverPageInfo = await _distributedServerInfoDBService.GetDistributedServerInfoDBByCodesAsync(request);
+                    if (serverPageInfo != null && serverPageInfo.Any()) {
+                        serverInformationList = serverPageInfo.Select(d => new ServerInformation
+                        {
+                            Code = d.ServerCode,
+                            Name = d.Name,
+                            Host = d.ServerUrl
+                        }).ToList();
+                    }
                 }
+                return serverInformationList;
+            }
+            catch (Exception ex) 
+            {
+                throw ex;
             }
-            return serverInformationList;
         }
 
         /// <summary>

+ 4 - 5
src/WingServer.cs

@@ -108,10 +108,6 @@ namespace WingCloudServer
                 }
             }
 
-            var fastestServerInteractionCenterService = new FastestServerInteractionCenterService();
-            _rpcHttpServer.RegisterService(typeof(WingInterfaceLibrary.Interface.IFastestServerInteractionCenterService), fastestServerInteractionCenterService);
-            fastestServerInteractionCenterService.Load(rpcClientPool);
-
             // AssemblyLoadContext.Default.Resolving += (assemblyLoadContext, assemblyName) =>
             // {                
             //     //var path = _assemblyDependencyResolver.ResolveUnmanagedDllToPath(assemblyName.FullName);
@@ -160,7 +156,10 @@ namespace WingCloudServer
                     //TODO
                 }
             }
- 
+
+            var fastestServerInteractionCenterService = new FastestServerInteractionCenterService();
+            _rpcHttpServer.RegisterService(typeof(WingInterfaceLibrary.Interface.IFastestServerInteractionCenterService), fastestServerInteractionCenterService);
+            fastestServerInteractionCenterService.Load(rpcClientPool);
         }
 
         private Type LoadService(string folder, object serviceName)