Browse Source

新增允许指定目录下匿名用户访问,提供Apk功能

lhio 2 years ago
parent
commit
1a49004e09

+ 3 - 3
.gitignore

@@ -1,3 +1,3 @@
-/bin
-/obj
-/.vs
+/bin
+/obj
+/.vs

+ 121 - 121
Controllers/L1SvrController.cs

@@ -1,121 +1,121 @@
-using LJLib.Client;
-using LJLib.Net.SPI.Client;
-using LJLib.Net.SPI.Com;
-using LJProxy.Models;
-using LJProxy.Settings;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Options;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using Newtonsoft.Json;
-using System.IO;
-using System.Text;
-using Newtonsoft.Json.Linq;
-using LJProxy.Services;
-using Microsoft.AspNetCore.Http.Extensions;
-using Microsoft.AspNetCore.Http;
-
-namespace LJProxy.Controllers
-{
-    [Route("api/[controller]")]
-    [ApiController]
-    public class L1SvrController : Controller
-    {
-        private static object _syncRoot = new object();
-        public static AppSettings _appSettingModel;
-        private LJClientPoolService _ljClient;
-        public L1SvrController(LJClientPoolService ljClient)
-        {
-            _ljClient = ljClient;
-        }
-
-        private string getIpAddress()
-        {
-            var ipAddress = Request.HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR");
-            if (!string.IsNullOrEmpty(ipAddress))
-            {
-                string[] addresses = ipAddress.Split(',');
-                if (addresses.Length > 0)
-                {
-                    return addresses[0];
-                }
-            }
-            return Request.HttpContext.GetServerVariable("REMOTE_ADDR");
-        }
-
-        [Route("svr/{apiName}")]
-        [HttpPost]
-        [HttpGet]
-        public async Task<IActionResult> Svr(string apiName)
-        {
-            var ipAddress = getIpAddress();
-            string requestBody;
-            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
-            {
-                requestBody = await reader.ReadToEndAsync();
-            }
-            var url = Request.GetDisplayUrl();
-            var pathStart = "/api/l1svr/svr/";
-            var idx = url.IndexOf(pathStart, StringComparison.OrdinalIgnoreCase);
-            string gateway = string.Empty;
-            if (idx > 0)
-                gateway = url.Substring(0, idx + 1);
-            if (!string.IsNullOrEmpty(requestBody))
-            {
-                var reqObj = JObject.Parse(requestBody);
-                reqObj["gateway"] = gateway;
-                if (!string.IsNullOrEmpty(ipAddress))
-                {
-                    reqObj["ip"] = ipAddress;
-                }
-                requestBody = JsonConvert.SerializeObject(reqObj);
-            }
-            var rslt = _ljClient.Pool.DoExcute(apiName, requestBody);
-            return Content(rslt, "application/json");
-        }
-
-        [HttpPost]
-        [Route("uploadfiles")]
-        [RequestFormLimits(ValueLengthLimit = 20 *1024 * 1024, MultipartBodyLengthLimit = 21*1024*1024)]
-        public IActionResult UploadFiles([FromForm] IFormCollection formData)
-        {
-            string token = string.Empty;
-            if (Request.Headers.ContainsKey("Authorization"))
-            {
-                token = Request.Headers["Authorization"];
-            }
-            var files = formData.Files;
-            if (files != null && files.Count > 0)
-            {
-                UploadFilesRequest requestObj = new UploadFilesRequest();
-                List<FileInfoModel> fileList = new List<FileInfoModel>();
-                requestObj.token = token;
-                foreach (var file in files)
-                {
-                    FileInfoModel fileInfo = new FileInfoModel();
-                    fileInfo.FileName = file.FileName;
-                    using (var fs = file.OpenReadStream())
-                    {
-                        byte[] buffer = new byte[fs.Length];
-                        fs.Read(buffer, 0, buffer.Length);
-                        fileInfo.FileData = Convert.ToBase64String(buffer);
-                    }
-                    fileList.Add(fileInfo);
-                }
-                requestObj.FileList = fileList;
-                var requestBody = JsonConvert.SerializeObject(requestObj);
-                var rslt = _ljClient.Pool.DoExcute(requestObj.GetApiName(), requestBody);
-                return Content(rslt, "application/json");
-            }
-            else
-            {
-                return NotFound();
-            }
-            
-        }
-
-
-    }
-}
+using LJLib.Client;
+using LJLib.Net.SPI.Client;
+using LJLib.Net.SPI.Com;
+using LJProxy.Models;
+using LJProxy.Settings;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Options;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+using System.IO;
+using System.Text;
+using Newtonsoft.Json.Linq;
+using LJProxy.Services;
+using Microsoft.AspNetCore.Http.Extensions;
+using Microsoft.AspNetCore.Http;
+
+namespace LJProxy.Controllers
+{
+    [Route("api/[controller]")]
+    [ApiController]
+    public class L1SvrController : Controller
+    {
+        private static object _syncRoot = new object();
+        public static AppSettings _appSettingModel;
+        private LJClientPoolService _ljClient;
+        public L1SvrController(LJClientPoolService ljClient)
+        {
+            _ljClient = ljClient;
+        }
+
+        private string getIpAddress()
+        {
+            var ipAddress = Request.HttpContext.GetServerVariable("HTTP_X_FORWARDED_FOR");
+            if (!string.IsNullOrEmpty(ipAddress))
+            {
+                string[] addresses = ipAddress.Split(',');
+                if (addresses.Length > 0)
+                {
+                    return addresses[0];
+                }
+            }
+            return Request.HttpContext.GetServerVariable("REMOTE_ADDR");
+        }
+
+        [Route("svr/{apiName}")]
+        [HttpPost]
+        [HttpGet]
+        public async Task<IActionResult> Svr(string apiName)
+        {
+            var ipAddress = getIpAddress();
+            string requestBody;
+            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
+            {
+                requestBody = await reader.ReadToEndAsync();
+            }
+            var url = Request.GetDisplayUrl();
+            var pathStart = "/api/l1svr/svr/";
+            var idx = url.IndexOf(pathStart, StringComparison.OrdinalIgnoreCase);
+            string gateway = string.Empty;
+            if (idx > 0)
+                gateway = url.Substring(0, idx + 1);
+            if (!string.IsNullOrEmpty(requestBody))
+            {
+                var reqObj = JObject.Parse(requestBody);
+                reqObj["gateway"] = gateway;
+                if (!string.IsNullOrEmpty(ipAddress))
+                {
+                    reqObj["ip"] = ipAddress;
+                }
+                requestBody = JsonConvert.SerializeObject(reqObj);
+            }
+            var rslt = _ljClient.Pool.DoExcute(apiName, requestBody);
+            return Content(rslt, "application/json");
+        }
+
+        [HttpPost]
+        [Route("uploadfiles")]
+        [RequestFormLimits(ValueLengthLimit = 20 *1024 * 1024, MultipartBodyLengthLimit = 21*1024*1024)]
+        public IActionResult UploadFiles([FromForm] IFormCollection formData)
+        {
+            string token = string.Empty;
+            if (Request.Headers.ContainsKey("Authorization"))
+            {
+                token = Request.Headers["Authorization"];
+            }
+            var files = formData.Files;
+            if (files != null && files.Count > 0)
+            {
+                UploadFilesRequest requestObj = new UploadFilesRequest();
+                List<FileInfoModel> fileList = new List<FileInfoModel>();
+                requestObj.token = token;
+                foreach (var file in files)
+                {
+                    FileInfoModel fileInfo = new FileInfoModel();
+                    fileInfo.FileName = file.FileName;
+                    using (var fs = file.OpenReadStream())
+                    {
+                        byte[] buffer = new byte[fs.Length];
+                        fs.Read(buffer, 0, buffer.Length);
+                        fileInfo.FileData = Convert.ToBase64String(buffer);
+                    }
+                    fileList.Add(fileInfo);
+                }
+                requestObj.FileList = fileList;
+                var requestBody = JsonConvert.SerializeObject(requestObj);
+                var rslt = _ljClient.Pool.DoExcute(requestObj.GetApiName(), requestBody);
+                return Content(rslt, "application/json");
+            }
+            else
+            {
+                return NotFound();
+            }
+            
+        }
+
+
+    }
+}

+ 41 - 41
Controllers/TestController.cs

@@ -1,41 +1,41 @@
-using LJLib.Client;
-using Microsoft.AspNetCore.Http.Extensions;
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace LJProxy.Controllers
-{
-    [Route("api/[controller]")]
-    public class TestController : Controller
-    {
-        private readonly IHttpClientFactory _clientFactory;
-        public TestController(IHttpClientFactory clientFactory)
-        {
-            _clientFactory = clientFactory;
-        }
-
-        //[HttpGet]
-        //[Route("test")]
-        //public string test()
-        //{
-        //    var creator = new DirectP1ClientCreator("192.168.0.92", Convert.ToInt32("7940"));
-        //    var pool = new LJClientPool(creator, 20);
-        //    var loginObj = new
-        //    {
-        //        accountname = "CRP1",
-        //        userid = "admin",
-        //        psw = "longjoe",
-        //        clientType = 10
-        //    };
-        //    var result=pool.DoExcute("ClientLogin", Newtonsoft.Json.JsonConvert.SerializeObject(loginObj));
-        //    return result;
-        //}
-
-    }
-}
+using LJLib.Client;
+using Microsoft.AspNetCore.Http.Extensions;
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net.Http;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace LJProxy.Controllers
+{
+    [Route("api/[controller]")]
+    public class TestController : Controller
+    {
+        private readonly IHttpClientFactory _clientFactory;
+        public TestController(IHttpClientFactory clientFactory)
+        {
+            _clientFactory = clientFactory;
+        }
+
+        //[HttpGet]
+        //[Route("test")]
+        //public string test()
+        //{
+        //    var creator = new DirectP1ClientCreator("192.168.0.92", Convert.ToInt32("7940"));
+        //    var pool = new LJClientPool(creator, 20);
+        //    var loginObj = new
+        //    {
+        //        accountname = "CRP1",
+        //        userid = "admin",
+        //        psw = "longjoe",
+        //        clientType = 10
+        //    };
+        //    var result=pool.DoExcute("ClientLogin", Newtonsoft.Json.JsonConvert.SerializeObject(loginObj));
+        //    return result;
+        //}
+
+    }
+}

+ 49 - 49
Controllers/VersionController.cs

@@ -1,49 +1,49 @@
-using LJProxy.Services;
-using Microsoft.AspNetCore.Mvc;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace LJProxy.Controllers
-{
-    [Route("api/[controller]")]
-    [ApiController]
-    public class VersionController: Controller
-    {
-        private VersionService _service;
-        public VersionController(VersionService vService)
-        {
-            _service = vService;
-        }
-
-        [Route("GetUpdateJson")]
-        [HttpGet]
-        [HttpPost]
-        public IActionResult GetUpdateJson()
-        {
-            string updateJson = _service.GetUpdateJson();
-            var result = new ContentResult();
-            result.Content = updateJson;
-            result.ContentType = "application/json";
-            return result;
-        }
-
-        [Route("GetAppUpdate/{apkName}")]
-        [HttpGet]
-        [HttpPost]
-        public IActionResult GetAppUpdate(string apkName)
-        {
-            var fs = _service.GetAPK(apkName);
-            if (fs == null)
-            {
-                return NotFound();
-            }
-            else
-            {
-                return new FileContentResult(fs, "application/vnd.android.package-archive");
-            }
-        }
-    }
-}
+using LJProxy.Services;
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace LJProxy.Controllers
+{
+    [Route("api/[controller]")]
+    [ApiController]
+    public class VersionController: Controller
+    {
+        private VersionService _service;
+        public VersionController(VersionService vService)
+        {
+            _service = vService;
+        }
+
+        [Route("GetUpdateJson")]
+        [HttpGet]
+        [HttpPost]
+        public IActionResult GetUpdateJson()
+        {
+            string updateJson = _service.GetUpdateJson();
+            var result = new ContentResult();
+            result.Content = updateJson;
+            result.ContentType = "application/json";
+            return result;
+        }
+
+        [Route("GetAppUpdate/{apkName}")]
+        [HttpGet]
+        [HttpPost]
+        public IActionResult GetAppUpdate(string apkName)
+        {
+            var fs = _service.GetAPK(apkName);
+            if (fs == null)
+            {
+                return NotFound();
+            }
+            else
+            {
+                return new FileContentResult(fs, "application/vnd.android.package-archive");
+            }
+        }
+    }
+}

+ 48 - 48
GlobalVar/Cache.cs

@@ -1,48 +1,48 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using System.Runtime.Caching;
-
-namespace LJProxy
-{
-    public static class Cache
-    {
-        public static MemoryCache DefaultCache
-        {
-            get
-            {
-                return MemoryCache.Default;
-            }
-        }
-
-        private static MemoryCache _fileCache = new MemoryCache("FileCache");
-        public static MemoryCache FileCache
-        {
-            get
-            {
-                return _fileCache;
-            }
-        }
-
-        public static CacheItemPolicy CreateCacheItemPolicy(TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null
-            , List<string> dependencyKeys = null, CacheItemPriority? priority = null)
-        {
-            var cachePolicy = new CacheItemPolicy();
-            if (slidingExpiration != null)
-                cachePolicy.SlidingExpiration = slidingExpiration.Value;
-            if (absoluteExpiration != null)
-                cachePolicy.AbsoluteExpiration = absoluteExpiration.Value;
-            if (dependencyKeys !=null && dependencyKeys.Count>0 )
-            {
-                cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(dependencyKeys));
-            }
-
-            if (priority != null)
-                cachePolicy.Priority = priority.Value;
-            else
-                cachePolicy.Priority = CacheItemPriority.Default;
-            return cachePolicy;
-        }
-    }
-}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Runtime.Caching;
+
+namespace LJProxy
+{
+    public static class Cache
+    {
+        public static MemoryCache DefaultCache
+        {
+            get
+            {
+                return MemoryCache.Default;
+            }
+        }
+
+        private static MemoryCache _fileCache = new MemoryCache("FileCache");
+        public static MemoryCache FileCache
+        {
+            get
+            {
+                return _fileCache;
+            }
+        }
+
+        public static CacheItemPolicy CreateCacheItemPolicy(TimeSpan? slidingExpiration = null, DateTime? absoluteExpiration = null
+            , List<string> dependencyKeys = null, CacheItemPriority? priority = null)
+        {
+            var cachePolicy = new CacheItemPolicy();
+            if (slidingExpiration != null)
+                cachePolicy.SlidingExpiration = slidingExpiration.Value;
+            if (absoluteExpiration != null)
+                cachePolicy.AbsoluteExpiration = absoluteExpiration.Value;
+            if (dependencyKeys !=null && dependencyKeys.Count>0 )
+            {
+                cachePolicy.ChangeMonitors.Add(new HostFileChangeMonitor(dependencyKeys));
+            }
+
+            if (priority != null)
+                cachePolicy.Priority = priority.Value;
+            else
+                cachePolicy.Priority = CacheItemPriority.Default;
+            return cachePolicy;
+        }
+    }
+}

+ 28 - 28
GlobalVar/GlobalVar.cs

@@ -1,28 +1,28 @@
-using LJLib.Net.SPI.Com;
-using LJProxy.Models;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using Newtonsoft.Json.Linq;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.Configuration;
-using LJProxy.Settings;
-
-namespace LJProxy
-{
-    public static class GlobalVar
-    {
-        public static AppSettings Setting { get; private set; }
-
-        public static void InitSetting(IConfiguration configuration)
-        {
-            Setting = new AppSettings();
-            Setting.L1SvrUrl = configuration.GetSection("L1SvrUrl")?.Value;
-            string threadSizeStr = configuration.GetSection("ThreadSize")?.Value;
-            Setting.ThreadSize = string.IsNullOrEmpty(threadSizeStr)?20:Convert.ToInt32(threadSizeStr);
-            Setting.ProxyDomainList = configuration.GetSection("ProxyDomainList").GetChildren().Select(c => c.Value).ToList();
-        }
-
-    }
-}
+using LJLib.Net.SPI.Com;
+using LJProxy.Models;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Newtonsoft.Json.Linq;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Configuration;
+using LJProxy.Settings;
+
+namespace LJProxy
+{
+    public static class GlobalVar
+    {
+        public static AppSettings Setting { get; private set; }
+
+        public static void InitSetting(IConfiguration configuration)
+        {
+            Setting = new AppSettings();
+            Setting.L1SvrUrl = configuration.GetSection("L1SvrUrl")?.Value;
+            string threadSizeStr = configuration.GetSection("ThreadSize")?.Value;
+            Setting.ThreadSize = string.IsNullOrEmpty(threadSizeStr)?20:Convert.ToInt32(threadSizeStr);
+            Setting.ProxyDomainList = configuration.GetSection("ProxyDomainList").GetChildren().Select(c => c.Value).ToList();
+        }
+
+    }
+}

+ 138 - 138
LJLib.IP/IPUtils.cs

@@ -1,138 +1,138 @@
-using System;
-using System.Diagnostics;
-using System.Net;
-using System.Net.Sockets;
-using System.Text.RegularExpressions;
-
-namespace LJLib.IP
-{
-    public static class IPUtils
-    {
-        [Obsolete("建议改用方法GetURLIPv4")]
-        public static string GetURLIP(string URL)
-        {
-            string ip = string.Empty;
-            try
-            {
-                IPHostEntry ipHost = Dns.GetHostEntry(URL);
-                bool haveip = false;
-                for (int i = 0; i < ipHost.AddressList.Length; i++)
-                {
-                    if (!haveip)
-                    {
-                        var tip = ipHost.AddressList[i].ToString();
-                        if (tip != "::1")
-                        {
-                            ip = tip;
-                            haveip = true;
-                        }
-                    }
-                }
-            }
-            catch (System.Exception ex)
-            {
-                Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString()));
-                ip = "获取龙嘉网失败:" + URL;
-            }
-            return ip;
-        }
-
-        /// <summary>
-        /// 返回URL的IPv4的地址
-        /// </summary>
-        /// <param name="URL">URL地址</param>
-        /// <returns>IPv4</returns>
-        public static IPAddress GetURLIPv4(string URL)
-        {
-            IPAddress ip = null;
-            if (IsIPv4Address(URL))
-            {
-                return IPAddress.Parse(URL);
-            }
-            try
-            {
-                var ipHost = Dns.GetHostEntry(URL);
-                foreach (var ipAddress in ipHost.AddressList)
-                {
-                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
-                    {
-                        if (!IPAddress.IsLoopback(ipAddress))
-                        {
-                            return ipAddress;
-                        }
-
-                        ip = ipAddress;
-                    }
-                }
-            }
-            catch (Exception ex)
-            {
-                Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString()));
-            }
-            return ip;
-        }
-
-        public static IPEndPoint GetIPEndPoint(string ipPortStr)
-        {
-            int index = ipPortStr.IndexOf(":");
-            if (index < 0)
-            {
-                throw new Exception(string.Format("ip:port不合法,{0}", ipPortStr));
-            }
-            var ipStr = ipPortStr.Substring(0, index);
-            var portStr = ipPortStr.Substring(index + 1);
-            try
-            {
-                var address = IPAddress.Parse(ipStr);
-                var port = int.Parse(portStr);
-                return new IPEndPoint(address, port);
-            }
-            catch (Exception ex)
-            {
-                throw new Exception(string.Format("ip:port不合法,{0},异常:{1}", ipPortStr, ex));
-            }
-        }
-
-        private static Regex r = null;
-
-        public static bool IsIPv4Address(string ip)
-        {
-            if (r == null)
-            {
-                r = new Regex(@"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
-            }
-            return r.IsMatch(ip);
-        }
-
-        /// <summary>
-        /// 判断TcpClient是否在连接
-        /// </summary>
-        public static bool IsConnecting(TcpClient tcpclient)
-        {
-            try
-            {
-                if (!tcpclient.Connected)
-                {
-                    return false;
-                }
-
-                var ifSelectRead = tcpclient.Client.Poll(1000, SelectMode.SelectRead);
-                if (!ifSelectRead) // 网络在连接无数据可读
-                {
-                    return true;
-                }
-
-                var ns = tcpclient.GetStream();
-                return ns.CanRead && ns.DataAvailable;
-            }
-            catch (Exception ex)
-            {
-                if (!(ex is ObjectDisposedException) && !(ex is InvalidOperationException))
-                {
-                    Trace.Write(ex.ToString());
-                }
-                return false;
-            }
-        }
-    }
-}
+using System;
+using System.Diagnostics;
+using System.Net;
+using System.Net.Sockets;
+using System.Text.RegularExpressions;
+
+namespace LJLib.IP
+{
+    public static class IPUtils
+    {
+        [Obsolete("建议改用方法GetURLIPv4")]
+        public static string GetURLIP(string URL)
+        {
+            string ip = string.Empty;
+            try
+            {
+                IPHostEntry ipHost = Dns.GetHostEntry(URL);
+                bool haveip = false;
+                for (int i = 0; i < ipHost.AddressList.Length; i++)
+                {
+                    if (!haveip)
+                    {
+                        var tip = ipHost.AddressList[i].ToString();
+                        if (tip != "::1")
+                        {
+                            ip = tip;
+                            haveip = true;
+                        }
+                    }
+                }
+            }
+            catch (System.Exception ex)
+            {
+                Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString()));
+                ip = "获取龙嘉网失败:" + URL;
+            }
+            return ip;
+        }
+
+        /// <summary>
+        /// 返回URL的IPv4的地址
+        /// </summary>
+        /// <param name="URL">URL地址</param>
+        /// <returns>IPv4</returns>
+        public static IPAddress GetURLIPv4(string URL)
+        {
+            IPAddress ip = null;
+            if (IsIPv4Address(URL))
+            {
+                return IPAddress.Parse(URL);
+            }
+            try
+            {
+                var ipHost = Dns.GetHostEntry(URL);
+                foreach (var ipAddress in ipHost.AddressList)
+                {
+                    if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
+                    {
+                        if (!IPAddress.IsLoopback(ipAddress))
+                        {
+                            return ipAddress;
+                        }
+
+                        ip = ipAddress;
+                    }
+                }
+            }
+            catch (Exception ex)
+            {
+                Debug.Write(string.Format("获取龙嘉网失败,URL:[{0}],{1}.", URL, ex.ToString()));
+            }
+            return ip;
+        }
+
+        public static IPEndPoint GetIPEndPoint(string ipPortStr)
+        {
+            int index = ipPortStr.IndexOf(":");
+            if (index < 0)
+            {
+                throw new Exception(string.Format("ip:port不合法,{0}", ipPortStr));
+            }
+            var ipStr = ipPortStr.Substring(0, index);
+            var portStr = ipPortStr.Substring(index + 1);
+            try
+            {
+                var address = IPAddress.Parse(ipStr);
+                var port = int.Parse(portStr);
+                return new IPEndPoint(address, port);
+            }
+            catch (Exception ex)
+            {
+                throw new Exception(string.Format("ip:port不合法,{0},异常:{1}", ipPortStr, ex));
+            }
+        }
+
+        private static Regex r = null;
+
+        public static bool IsIPv4Address(string ip)
+        {
+            if (r == null)
+            {
+                r = new Regex(@"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
+            }
+            return r.IsMatch(ip);
+        }
+
+        /// <summary>
+        /// 判断TcpClient是否在连接
+        /// </summary>
+        public static bool IsConnecting(TcpClient tcpclient)
+        {
+            try
+            {
+                if (!tcpclient.Connected)
+                {
+                    return false;
+                }
+
+                var ifSelectRead = tcpclient.Client.Poll(1000, SelectMode.SelectRead);
+                if (!ifSelectRead) // 网络在连接无数据可读
+                {
+                    return true;
+                }
+
+                var ns = tcpclient.GetStream();
+                return ns.CanRead && ns.DataAvailable;
+            }
+            catch (Exception ex)
+            {
+                if (!(ex is ObjectDisposedException) && !(ex is InvalidOperationException))
+                {
+                    Trace.Write(ex.ToString());
+                }
+                return false;
+            }
+        }
+    }
+}

+ 13 - 13
LJLib.Net.SPI.Client/ILJClient.cs

@@ -1,13 +1,13 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-
-namespace LJLib.Net.SPI.Client
-{
-    public interface ILJClient : IDisposable
-    {
-        string DoExcute(string apiName, string requestJSON);
-        void Beat();
-        void Dispose();
-    }
-}
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace LJLib.Net.SPI.Client
+{
+    public interface ILJClient : IDisposable
+    {
+        string DoExcute(string apiName, string requestJSON);
+        void Beat();
+        void Dispose();
+    }
+}

+ 11 - 11
LJLib.Net.SPI.Com/ErrResponse.cs

@@ -1,12 +1,12 @@
-
-namespace LJLib.Net.SPI.Com
-{
-    internal sealed class ErrResponse : LJResponse
-    {
-        public ErrResponse() { }
-        public ErrResponse(string errmsg)
-        {
-            this.ErrMsg = errmsg;
-        }
-    }
+
+namespace LJLib.Net.SPI.Com
+{
+    internal sealed class ErrResponse : LJResponse
+    {
+        public ErrResponse() { }
+        public ErrResponse(string errmsg)
+        {
+            this.ErrMsg = errmsg;
+        }
+    }
 }

+ 17 - 17
LJLib.Net.SPI.Com/ILJRequest.cs

@@ -1,17 +1,17 @@
-
-namespace LJLib.Net.SPI.Com
-{
-    public interface ILJRequest
-    {
-        string GetApiName();
-    }
-
-    public abstract class LJRequest: ILJRequest 
-    {
-        public string GetApiName()
-        {
-            var typeName = this.GetType().Name;
-            return typeName.Substring(0, typeName.Length - 7);
-        }
-    }
-}
+
+namespace LJLib.Net.SPI.Com
+{
+    public interface ILJRequest
+    {
+        string GetApiName();
+    }
+
+    public abstract class LJRequest: ILJRequest 
+    {
+        public string GetApiName()
+        {
+            var typeName = this.GetType().Name;
+            return typeName.Substring(0, typeName.Length - 7);
+        }
+    }
+}

+ 23 - 23
LJLib.Net.SPI.Com/LJResponse.cs

@@ -1,23 +1,23 @@
-
-namespace LJLib.Net.SPI.Com
-{
-    public abstract class LJResponse
-    {
-        /// <summary>
-        /// 错误代码
-        /// </summary>
-        public string ErrCode { get; set; }
-        /// <summary>
-        /// 错误信息
-        /// </summary>
-        public string ErrMsg { get; set; }
-        /// <summary>
-        /// 异常详细信息
-        /// </summary>
-        public string DebugMsg { get; set; }
-
-        public string AppErrCode { get; set; }
-        public string AppErrMsg { get; set; }
-
-    }
-}
+
+namespace LJLib.Net.SPI.Com
+{
+    public abstract class LJResponse
+    {
+        /// <summary>
+        /// 错误代码
+        /// </summary>
+        public string ErrCode { get; set; }
+        /// <summary>
+        /// 错误信息
+        /// </summary>
+        public string ErrMsg { get; set; }
+        /// <summary>
+        /// 异常详细信息
+        /// </summary>
+        public string DebugMsg { get; set; }
+
+        public string AppErrCode { get; set; }
+        public string AppErrMsg { get; set; }
+
+    }
+}

+ 33 - 33
LJLib.TcpClient/DirectP1ClientCreator.cs

@@ -1,33 +1,33 @@
-using LJLib.Net.SPI.Client;
-using System;
-using System.Net;
-using System.Net.Sockets;
-using LJLib.IP;
-
-namespace LJLib.Client
-{
-    public sealed class DirectP1ClientCreator : LJClientCreator
-    {
-        private string _url;
-        private IPAddress _ip = null;
-        private int _port;
-
-        public DirectP1ClientCreator(String url, int port)
-        {
-            _url = url;
-            _port = port;
-        }
-
-        public override ILJClient newClient()
-        {
-            if (_ip == null)
-            {
-                _ip = IPUtils.GetURLIPv4(_url);
-            }
-
-            var tcpClient = new TcpClient();
-            tcpClient.Connect(_ip, _port);
-            return new P1Client(tcpClient.GetStream());
-        }
-    }
-}
+using LJLib.Net.SPI.Client;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using LJLib.IP;
+
+namespace LJLib.Client
+{
+    public sealed class DirectP1ClientCreator : LJClientCreator
+    {
+        private string _url;
+        private IPAddress _ip = null;
+        private int _port;
+
+        public DirectP1ClientCreator(String url, int port)
+        {
+            _url = url;
+            _port = port;
+        }
+
+        public override ILJClient newClient()
+        {
+            if (_ip == null)
+            {
+                _ip = IPUtils.GetURLIPv4(_url);
+            }
+
+            var tcpClient = new TcpClient();
+            tcpClient.Connect(_ip, _port);
+            return new P1Client(tcpClient.GetStream());
+        }
+    }
+}

+ 9 - 9
LJLib.TcpClient/LJClientCreator.cs

@@ -1,9 +1,9 @@
-using LJLib.Net.SPI.Client;
-
-namespace LJLib.Client
-{
-    public abstract class LJClientCreator
-    {
-        public abstract ILJClient newClient();
-    }
-}
+using LJLib.Net.SPI.Client;
+
+namespace LJLib.Client
+{
+    public abstract class LJClientCreator
+    {
+        public abstract ILJClient newClient();
+    }
+}

+ 140 - 140
LJLib.TcpClient/LJClientPool.cs

@@ -1,140 +1,140 @@
-using LJLib.Net.SPI.Client;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Threading;
-
-namespace LJLib.Client
-{
-    public sealed class LJClientPool : ILJClient
-    {
-        private const int DEFAULT_RETRY_COUNT = 1;
-
-        private LJClientCreator _creator;
-        private ILJClient[] _clients;
-        private bool[] _client_states;
-        private object _syncRoot = new object();
-
-        public LJClientPool(LJClientCreator creator, int size)
-        {
-            _creator = creator;
-            _clients = new ILJClient[size];
-            _client_states = new bool[size];
-            for (int i = 0; i < size; i++)
-            {
-                _clients[i] = null;
-                _client_states[i] = false;
-            }
-        }
-        public string DoExcute(string apiName, string requestJSON)
-        {
-            int i;
-            do
-            {
-                lock (_syncRoot)
-                {
-                    for (i = 0; i < _client_states.Length; i++)
-                    {
-                        if (!_client_states[i])
-                        {
-                            _client_states[i] = true;
-                            break;
-                        }
-                    }
-                }
-                if (i >= _client_states.Length)
-                {
-                    Thread.Sleep(100);
-                }
-            } while (i >= _client_states.Length);
-
-            try
-            {
-                int retry = 0;
-                string rslt = null;
-                while (retry <= DEFAULT_RETRY_COUNT)
-                {
-                    try
-                    {
-                        if (_clients[i] == null)
-                        {
-                            _clients[i] = _creator.newClient();
-                        }
-                        rslt = _clients[i].DoExcute(apiName, requestJSON);
-                        break;
-                    }
-                    catch (Exception e)
-                    {
-                        Trace.Write(e.ToString());
-                        if (_clients[i] != null)
-                        {
-                            _clients[i].Dispose();
-                            _clients[i] = null;
-                        }
-                        ++retry;
-                        if (retry > DEFAULT_RETRY_COUNT)
-                        {
-                            throw e;//大于重试次数时异常重抛
-                        }
-                    }
-                }
-                return rslt;
-            }
-            catch (Exception ex)
-            {
-                Trace.Write(ex.ToString());
-                return ex.ToString();
-            }
-            finally
-            {
-                _client_states[i] = false;
-            }
-        }
-
-        public void Beat()
-        {
-            for (int i = 0; i < _client_states.Length; i++)
-            {
-                lock (_syncRoot)
-                {
-                    if (_client_states[i])
-                    {
-                        continue;
-                    }
-                    _client_states[i] = true;
-                }
-                try
-                {
-                    //空实例无须心跳
-                    if (_clients[i] != null)
-                    {
-                        _clients[i].Beat();
-                    }
-                }
-                catch (Exception e)
-                {
-                    _clients[i].Dispose();
-                    _clients[i] = null;
-                    Trace.Write("连接池请求异常" + e.ToString());
-                }
-                finally
-                {
-                    _client_states[i] = false;
-                }
-            }
-        }
-
-        public void Dispose()
-        {
-            for (int i = 0; i < _clients.Length; i++)
-            {
-                if (_clients[i] != null)
-                {
-                    _clients[i].Dispose();
-                    _clients[i] = null;
-                }
-            }
-        }
-
-    }
-}
+using LJLib.Net.SPI.Client;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading;
+
+namespace LJLib.Client
+{
+    public sealed class LJClientPool : ILJClient
+    {
+        private const int DEFAULT_RETRY_COUNT = 1;
+
+        private LJClientCreator _creator;
+        private ILJClient[] _clients;
+        private bool[] _client_states;
+        private object _syncRoot = new object();
+
+        public LJClientPool(LJClientCreator creator, int size)
+        {
+            _creator = creator;
+            _clients = new ILJClient[size];
+            _client_states = new bool[size];
+            for (int i = 0; i < size; i++)
+            {
+                _clients[i] = null;
+                _client_states[i] = false;
+            }
+        }
+        public string DoExcute(string apiName, string requestJSON)
+        {
+            int i;
+            do
+            {
+                lock (_syncRoot)
+                {
+                    for (i = 0; i < _client_states.Length; i++)
+                    {
+                        if (!_client_states[i])
+                        {
+                            _client_states[i] = true;
+                            break;
+                        }
+                    }
+                }
+                if (i >= _client_states.Length)
+                {
+                    Thread.Sleep(100);
+                }
+            } while (i >= _client_states.Length);
+
+            try
+            {
+                int retry = 0;
+                string rslt = null;
+                while (retry <= DEFAULT_RETRY_COUNT)
+                {
+                    try
+                    {
+                        if (_clients[i] == null)
+                        {
+                            _clients[i] = _creator.newClient();
+                        }
+                        rslt = _clients[i].DoExcute(apiName, requestJSON);
+                        break;
+                    }
+                    catch (Exception e)
+                    {
+                        Trace.Write(e.ToString());
+                        if (_clients[i] != null)
+                        {
+                            _clients[i].Dispose();
+                            _clients[i] = null;
+                        }
+                        ++retry;
+                        if (retry > DEFAULT_RETRY_COUNT)
+                        {
+                            throw e;//大于重试次数时异常重抛
+                        }
+                    }
+                }
+                return rslt;
+            }
+            catch (Exception ex)
+            {
+                Trace.Write(ex.ToString());
+                return ex.ToString();
+            }
+            finally
+            {
+                _client_states[i] = false;
+            }
+        }
+
+        public void Beat()
+        {
+            for (int i = 0; i < _client_states.Length; i++)
+            {
+                lock (_syncRoot)
+                {
+                    if (_client_states[i])
+                    {
+                        continue;
+                    }
+                    _client_states[i] = true;
+                }
+                try
+                {
+                    //空实例无须心跳
+                    if (_clients[i] != null)
+                    {
+                        _clients[i].Beat();
+                    }
+                }
+                catch (Exception e)
+                {
+                    _clients[i].Dispose();
+                    _clients[i] = null;
+                    Trace.Write("连接池请求异常" + e.ToString());
+                }
+                finally
+                {
+                    _client_states[i] = false;
+                }
+            }
+        }
+
+        public void Dispose()
+        {
+            for (int i = 0; i < _clients.Length; i++)
+            {
+                if (_clients[i] != null)
+                {
+                    _clients[i].Dispose();
+                    _clients[i] = null;
+                }
+            }
+        }
+
+    }
+}

+ 264 - 264
LJLib.TcpClient/P1Client.cs

@@ -1,264 +1,264 @@
-using LJLib.Net.SPI.Client;
-using LJLib.Tools.Helper;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.IO.Compression;
-using System.Text;
-using System.Threading;
-
-namespace LJLib.Client
-{
-    public sealed class P1Client : ILJClient
-    {
-        private const byte NEW_ALLGZIP = 0x10;
-        private const byte SVRBEAT = 0x08;
-        private const byte PROTOCOL_FLAG = 0x04;
-        private const byte READ_GZIP = 0x02;
-        private const byte WRITE_GZIP = 0x01;
-
-        private Stream _stream = null;
-
-        private object syncRoot = new object();
-
-        public P1Client(Stream stream)
-        {
-            _stream = stream;
-        }
-
-        public string DoExcute(string apiName, string requestJSON)
-        {
-            lock (syncRoot)
-            {
-                var apiname = apiName;
-
-                var firstByte = new[]
-                {
-                    (byte)(SVRBEAT | PROTOCOL_FLAG | READ_GZIP | WRITE_GZIP | NEW_ALLGZIP),
-                    (byte)(SVRBEAT | PROTOCOL_FLAG | READ_GZIP | WRITE_GZIP),
-                    (byte)(SVRBEAT | PROTOCOL_FLAG),
-                };
-
-                var headByte = firstByte[0];
-                if (headByte > 0x1F || (headByte & PROTOCOL_FLAG) != PROTOCOL_FLAG)
-                {
-                    throw new Exception("不支持协议" + headByte.ToString("X2"));
-                }
-
-                if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
-                {
-                    if ((headByte & READ_GZIP) != READ_GZIP)
-                    {
-                        throw new Exception("协议异常:新协议必须压缩发送");
-                    }
-                    if ((headByte & WRITE_GZIP) != WRITE_GZIP)
-                    {
-                        throw new Exception("协议异常:新协议必须压缩返回");
-                    }
-                }
-
-
-                if (!_stream.CanWrite)
-                {
-                    throw new Exception(string.Format("远端服务已中断(不能写)"));
-                }
-
-                _stream.Write(firstByte, 0, 1);
-
-                var ostream = _stream;
-
-                if ((headByte & READ_GZIP) == READ_GZIP)
-                {
-                    ostream = new MemoryStream();
-                }
-
-                string str = apiname + requestJSON;
-
-                WriteStringAndFiles(ostream, str, null, null);
-
-                if ((headByte & READ_GZIP) == READ_GZIP)
-                {
-                    using (ostream)
-                    using (var gzipms = new MemoryStream())
-                    using (var gzip = new GZipStream(gzipms, CompressionMode.Compress, true))
-                    {
-                        ostream.Seek(0, SeekOrigin.Begin);
-                        StreamHelper.StreamCopy(gzip, ostream);
-                        gzip.Close();
-
-                        if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
-                        {
-                            var filelen = BitConverter.GetBytes((int)gzipms.Length);
-                            _stream.Write(filelen, 0, filelen.Length);
-                        }
-
-                        gzipms.Seek(0, SeekOrigin.Begin);
-                        StreamHelper.StreamCopy(_stream, gzipms);
-                    }
-                }
-
-                if (!_stream.CanRead)
-                {
-                    throw new Exception(string.Format("远端服务已中断(不能读)"));
-                }
-                if ((headByte & SVRBEAT) == SVRBEAT)
-                {
-                    var oldTimeout = _stream.ReadTimeout;
-                    _stream.ReadTimeout = 10000;
-                    var hasRslt = _stream.ReadByte();
-                    while (hasRslt == 0)
-                    {
-                        Thread.Sleep(100);
-                        if (!_stream.CanRead)
-                        {
-                            throw new Exception(string.Format("远端服务已中断(不能读)"));
-                        }
-                        hasRslt = _stream.ReadByte();
-                        if (hasRslt == -1)
-                        {
-                            throw new Exception(string.Format("远端服务已中断(不能读)"));
-                        }
-                    }
-                    _stream.ReadTimeout = oldTimeout;
-                }
-
-                Debug.Write("WaitServer End");
-
-                var istream = _stream;
-
-                MemoryStream ms = null;
-                GZipStream gzipstream = null;
-
-                if ((headByte & WRITE_GZIP) == WRITE_GZIP)
-                {
-                    if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
-                    {
-                        ms = new MemoryStream();
-                        var allen = new byte[4];
-                        _stream.Read(allen, 0, allen.Length);
-                        var alen = BitConverter.ToInt32(allen, 0);
-
-                        StreamHelper.StreamCopy(ms, _stream, alen);
-
-                        Debug.Write("ReadResponseFromNet End");
-                        ms.Seek(0, SeekOrigin.Begin);
-                        gzipstream = new GZipStream(ms, CompressionMode.Decompress, false);
-                        istream = gzipstream;
-                    }
-                    else
-                    {
-                        gzipstream = new GZipStream(_stream, CompressionMode.Decompress, true);
-                        istream = gzipstream;
-                    }
-                }
-
-                byte[] bytes;
-                Dictionary<string, byte[]> rfiles = new Dictionary<string, byte[]>();
-                using (ms)
-                using (gzipstream)
-                {
-                    var reader = new BinaryReader(istream);
-                    var len = reader.ReadInt32();
-                    bytes = reader.ReadBytes(len);
-
-                    var filecnt = reader.ReadByte();
-                    for (int i = 0; i < filecnt; i++)
-                    {
-                        var namelen = reader.ReadInt32();
-                        var namebytes = reader.ReadBytes(namelen);
-                        var datalen = reader.ReadInt32();
-                        var databytes = reader.ReadBytes(datalen);
-                        rfiles.Add(Encoding.UTF8.GetString(namebytes), databytes);
-                    }
-                    Debug.Write("ReadResponse End");
-                }
-
-                var strrsp = Encoding.UTF8.GetString(bytes);
-                return strrsp;
-            }
-        }
-
-        private static void WriteStringAndFiles(Stream ostream, string str, IDictionary<string, string> files, Dictionary<string, byte[]> exfiles)
-        {
-            var strbytes = Encoding.UTF8.GetBytes(str);
-            var lenbytes = BitConverter.GetBytes(strbytes.Length);
-            ostream.Write(lenbytes, 0, lenbytes.Length);
-            ostream.Write(strbytes, 0, strbytes.Length);
-            ostream.Flush();
-
-            if (files == null)
-            {
-                files = new Dictionary<string, string>();
-            }
-
-            if (exfiles == null)
-            {
-                exfiles = new Dictionary<string, byte[]>();
-            }
-
-            var shortbytes = BitConverter.GetBytes((short)(files.Count + exfiles.Count));
-            ostream.Write(shortbytes, 0, shortbytes.Length);
-
-            foreach (var file in files)
-            {
-                var namebytes = Encoding.UTF8.GetBytes(file.Key);
-                var namelen = BitConverter.GetBytes(namebytes.Length);
-                ostream.Write(namelen, 0, namelen.Length);
-                ostream.Write(namebytes, 0, namebytes.Length);
-                ostream.Flush();
-
-                using (var fs = File.OpenRead(file.Value))
-                {
-                    var filelen = BitConverter.GetBytes((int)fs.Length);
-                    ostream.Write(filelen, 0, filelen.Length);
-                    byte[] buff = new byte[10240];
-                    int read = 0;
-                    while ((read = fs.Read(buff, 0, buff.Length)) > 0)
-                    {
-                        ostream.Write(buff, 0, read);
-                        ostream.Flush();
-                    }
-                }
-            }
-
-            foreach (var file in exfiles)
-            {
-                var namebytes = Encoding.UTF8.GetBytes(file.Key);
-                var namelen = BitConverter.GetBytes(namebytes.Length);
-                ostream.Write(namelen, 0, namelen.Length);
-                ostream.Write(namebytes, 0, namebytes.Length);
-                ostream.Flush();
-                var filelen = BitConverter.GetBytes((int)file.Value.Length);
-                ostream.Write(filelen, 0, filelen.Length);
-
-                using (var ms = new MemoryStream(file.Value))
-                {
-                    byte[] buff = new byte[10240];
-                    int read = 0;
-                    while ((read = ms.Read(buff, 0, buff.Length)) > 0)
-                    {
-                        ostream.Write(buff, 0, read);
-                        ostream.Flush();
-                    }
-                }
-                ostream.Flush();
-            }
-
-            ostream.Flush();
-        }
-
-        public void Beat()
-        {
-            lock (syncRoot)
-            {
-                _stream.WriteByte(0x00);
-            }
-        }
-
-        public void Dispose()
-        {
-            _stream.Dispose();
-        }
-    }
-}
+using LJLib.Net.SPI.Client;
+using LJLib.Tools.Helper;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.IO.Compression;
+using System.Text;
+using System.Threading;
+
+namespace LJLib.Client
+{
+    public sealed class P1Client : ILJClient
+    {
+        private const byte NEW_ALLGZIP = 0x10;
+        private const byte SVRBEAT = 0x08;
+        private const byte PROTOCOL_FLAG = 0x04;
+        private const byte READ_GZIP = 0x02;
+        private const byte WRITE_GZIP = 0x01;
+
+        private Stream _stream = null;
+
+        private object syncRoot = new object();
+
+        public P1Client(Stream stream)
+        {
+            _stream = stream;
+        }
+
+        public string DoExcute(string apiName, string requestJSON)
+        {
+            lock (syncRoot)
+            {
+                var apiname = apiName;
+
+                var firstByte = new[]
+                {
+                    (byte)(SVRBEAT | PROTOCOL_FLAG | READ_GZIP | WRITE_GZIP | NEW_ALLGZIP),
+                    (byte)(SVRBEAT | PROTOCOL_FLAG | READ_GZIP | WRITE_GZIP),
+                    (byte)(SVRBEAT | PROTOCOL_FLAG),
+                };
+
+                var headByte = firstByte[0];
+                if (headByte > 0x1F || (headByte & PROTOCOL_FLAG) != PROTOCOL_FLAG)
+                {
+                    throw new Exception("不支持协议" + headByte.ToString("X2"));
+                }
+
+                if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
+                {
+                    if ((headByte & READ_GZIP) != READ_GZIP)
+                    {
+                        throw new Exception("协议异常:新协议必须压缩发送");
+                    }
+                    if ((headByte & WRITE_GZIP) != WRITE_GZIP)
+                    {
+                        throw new Exception("协议异常:新协议必须压缩返回");
+                    }
+                }
+
+
+                if (!_stream.CanWrite)
+                {
+                    throw new Exception(string.Format("远端服务已中断(不能写)"));
+                }
+
+                _stream.Write(firstByte, 0, 1);
+
+                var ostream = _stream;
+
+                if ((headByte & READ_GZIP) == READ_GZIP)
+                {
+                    ostream = new MemoryStream();
+                }
+
+                string str = apiname + requestJSON;
+
+                WriteStringAndFiles(ostream, str, null, null);
+
+                if ((headByte & READ_GZIP) == READ_GZIP)
+                {
+                    using (ostream)
+                    using (var gzipms = new MemoryStream())
+                    using (var gzip = new GZipStream(gzipms, CompressionMode.Compress, true))
+                    {
+                        ostream.Seek(0, SeekOrigin.Begin);
+                        StreamHelper.StreamCopy(gzip, ostream);
+                        gzip.Close();
+
+                        if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
+                        {
+                            var filelen = BitConverter.GetBytes((int)gzipms.Length);
+                            _stream.Write(filelen, 0, filelen.Length);
+                        }
+
+                        gzipms.Seek(0, SeekOrigin.Begin);
+                        StreamHelper.StreamCopy(_stream, gzipms);
+                    }
+                }
+
+                if (!_stream.CanRead)
+                {
+                    throw new Exception(string.Format("远端服务已中断(不能读)"));
+                }
+                if ((headByte & SVRBEAT) == SVRBEAT)
+                {
+                    var oldTimeout = _stream.ReadTimeout;
+                    _stream.ReadTimeout = 10000;
+                    var hasRslt = _stream.ReadByte();
+                    while (hasRslt == 0)
+                    {
+                        Thread.Sleep(100);
+                        if (!_stream.CanRead)
+                        {
+                            throw new Exception(string.Format("远端服务已中断(不能读)"));
+                        }
+                        hasRslt = _stream.ReadByte();
+                        if (hasRslt == -1)
+                        {
+                            throw new Exception(string.Format("远端服务已中断(不能读)"));
+                        }
+                    }
+                    _stream.ReadTimeout = oldTimeout;
+                }
+
+                Debug.Write("WaitServer End");
+
+                var istream = _stream;
+
+                MemoryStream ms = null;
+                GZipStream gzipstream = null;
+
+                if ((headByte & WRITE_GZIP) == WRITE_GZIP)
+                {
+                    if ((headByte & NEW_ALLGZIP) == NEW_ALLGZIP)
+                    {
+                        ms = new MemoryStream();
+                        var allen = new byte[4];
+                        _stream.Read(allen, 0, allen.Length);
+                        var alen = BitConverter.ToInt32(allen, 0);
+
+                        StreamHelper.StreamCopy(ms, _stream, alen);
+
+                        Debug.Write("ReadResponseFromNet End");
+                        ms.Seek(0, SeekOrigin.Begin);
+                        gzipstream = new GZipStream(ms, CompressionMode.Decompress, false);
+                        istream = gzipstream;
+                    }
+                    else
+                    {
+                        gzipstream = new GZipStream(_stream, CompressionMode.Decompress, true);
+                        istream = gzipstream;
+                    }
+                }
+
+                byte[] bytes;
+                Dictionary<string, byte[]> rfiles = new Dictionary<string, byte[]>();
+                using (ms)
+                using (gzipstream)
+                {
+                    var reader = new BinaryReader(istream);
+                    var len = reader.ReadInt32();
+                    bytes = reader.ReadBytes(len);
+
+                    var filecnt = reader.ReadByte();
+                    for (int i = 0; i < filecnt; i++)
+                    {
+                        var namelen = reader.ReadInt32();
+                        var namebytes = reader.ReadBytes(namelen);
+                        var datalen = reader.ReadInt32();
+                        var databytes = reader.ReadBytes(datalen);
+                        rfiles.Add(Encoding.UTF8.GetString(namebytes), databytes);
+                    }
+                    Debug.Write("ReadResponse End");
+                }
+
+                var strrsp = Encoding.UTF8.GetString(bytes);
+                return strrsp;
+            }
+        }
+
+        private static void WriteStringAndFiles(Stream ostream, string str, IDictionary<string, string> files, Dictionary<string, byte[]> exfiles)
+        {
+            var strbytes = Encoding.UTF8.GetBytes(str);
+            var lenbytes = BitConverter.GetBytes(strbytes.Length);
+            ostream.Write(lenbytes, 0, lenbytes.Length);
+            ostream.Write(strbytes, 0, strbytes.Length);
+            ostream.Flush();
+
+            if (files == null)
+            {
+                files = new Dictionary<string, string>();
+            }
+
+            if (exfiles == null)
+            {
+                exfiles = new Dictionary<string, byte[]>();
+            }
+
+            var shortbytes = BitConverter.GetBytes((short)(files.Count + exfiles.Count));
+            ostream.Write(shortbytes, 0, shortbytes.Length);
+
+            foreach (var file in files)
+            {
+                var namebytes = Encoding.UTF8.GetBytes(file.Key);
+                var namelen = BitConverter.GetBytes(namebytes.Length);
+                ostream.Write(namelen, 0, namelen.Length);
+                ostream.Write(namebytes, 0, namebytes.Length);
+                ostream.Flush();
+
+                using (var fs = File.OpenRead(file.Value))
+                {
+                    var filelen = BitConverter.GetBytes((int)fs.Length);
+                    ostream.Write(filelen, 0, filelen.Length);
+                    byte[] buff = new byte[10240];
+                    int read = 0;
+                    while ((read = fs.Read(buff, 0, buff.Length)) > 0)
+                    {
+                        ostream.Write(buff, 0, read);
+                        ostream.Flush();
+                    }
+                }
+            }
+
+            foreach (var file in exfiles)
+            {
+                var namebytes = Encoding.UTF8.GetBytes(file.Key);
+                var namelen = BitConverter.GetBytes(namebytes.Length);
+                ostream.Write(namelen, 0, namelen.Length);
+                ostream.Write(namebytes, 0, namebytes.Length);
+                ostream.Flush();
+                var filelen = BitConverter.GetBytes((int)file.Value.Length);
+                ostream.Write(filelen, 0, filelen.Length);
+
+                using (var ms = new MemoryStream(file.Value))
+                {
+                    byte[] buff = new byte[10240];
+                    int read = 0;
+                    while ((read = ms.Read(buff, 0, buff.Length)) > 0)
+                    {
+                        ostream.Write(buff, 0, read);
+                        ostream.Flush();
+                    }
+                }
+                ostream.Flush();
+            }
+
+            ostream.Flush();
+        }
+
+        public void Beat()
+        {
+            lock (syncRoot)
+            {
+                _stream.WriteByte(0x00);
+            }
+        }
+
+        public void Dispose()
+        {
+            _stream.Dispose();
+        }
+    }
+}

+ 33 - 24
LJProxy.csproj

@@ -1,24 +1,33 @@
-<Project Sdk="Microsoft.NET.Sdk.Web">
-
-  <PropertyGroup>
-    <TargetFramework>netcoreapp3.1</TargetFramework>
-  </PropertyGroup>
-
-  <ItemGroup>
-    <None Include="LJProxy.sln" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <PackageReference Include="AndroidXml" Version="1.1.22" />
-    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.18" />
-    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
-    <PackageReference Include="SharpZipLib.NETStandard" Version="1.0.7" />
-    <PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
-  </ItemGroup>
-
-  <ItemGroup>
-    <Folder Include="apk\" />
-  </ItemGroup>
-
-
-</Project>
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+  <PropertyGroup>
+    <TargetFramework>net6.0</TargetFramework>
+    <StartupObject></StartupObject>
+    <PlatformTarget>AnyCPU</PlatformTarget>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <None Include="LJProxy.sln" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <PackageReference Include="AndroidXml" Version="1.1.22" />
+    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.18" />
+    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
+    <PackageReference Include="SharpZipLib.NETStandard" Version="1.0.7" />
+    <PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Folder Include="apk\" />
+  </ItemGroup>
+
+  <ItemGroup>
+    <Content Update="wwwroot\anyC84F3B0582994A1184044B116EC2080B\index.html">
+      <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
+      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
+    </Content>
+  </ItemGroup>
+
+
+</Project>

+ 12 - 8
LJProxy.csproj.user

@@ -1,9 +1,13 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <PropertyGroup>
-    <Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
-    <Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
-    <ShowAllFiles>false</ShowAllFiles>
-    <NameOfLastUsedPublishProfile>F:\projects\LJProxy\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
-  </PropertyGroup>
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
+    <Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
+    <ShowAllFiles>false</ShowAllFiles>
+    <NameOfLastUsedPublishProfile>C:\myfiles\longjoe\projects\LJProxy\Properties\PublishProfiles\FolderProfile.pubxml</NameOfLastUsedPublishProfile>
+    <ActiveDebugProfile>LJProxy</ActiveDebugProfile>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
+    <DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
+  </PropertyGroup>
 </Project>

+ 25 - 25
LJProxy.sln

@@ -1,25 +1,25 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 16
-VisualStudioVersion = 16.0.31424.327
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LJProxy", "LJProxy.csproj", "{4B29784A-E029-4796-94B8-9C1EA47813D9}"
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Any CPU = Debug|Any CPU
-		Release|Any CPU = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Release|Any CPU.Build.0 = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-	GlobalSection(ExtensibilityGlobals) = postSolution
-		SolutionGuid = {E61F7846-99DE-4F18-A547-3F1C32D692B2}
-	EndGlobalSection
-EndGlobal
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.31424.327
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LJProxy", "LJProxy.csproj", "{4B29784A-E029-4796-94B8-9C1EA47813D9}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{4B29784A-E029-4796-94B8-9C1EA47813D9}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {E61F7846-99DE-4F18-A547-3F1C32D692B2}
+	EndGlobalSection
+EndGlobal

+ 59 - 59
LocalLog/LocalTraceListener.cs

@@ -1,60 +1,60 @@
-using LJLib.Tools.File;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-
-namespace LJLib.LocalLog
-{
-    internal class LocalTraceListener : TraceListener
-    {
-#if !(WindowsCE || PocketPC)
-        private Dictionary<string, byte> oldStack = new Dictionary<string, byte>();
-#endif
-
-        private object _syncRoot = new object();
-
-        private ILogger _logger = null;
-        public bool HasStack { get; set; }
-        public LocalTraceListener(ILogger logger) { _logger = logger; }
-        public override void Write(string message)
-        {
-            lock (_syncRoot)
-            {
-                if (_logger != null)
-                {
-                    try
-                    {
-                        if (HasStack) // 包含堆栈信息
-                        {
-#if !(WindowsCE || PocketPC)
-                            var stack = (new StackTrace()).ToString();
-                            var key = stack;
-                            var index = message.IndexOf(": ");
-                            if (index >= 0)
-                            {
-                                key += message.Substring(0, index);
-                            }
-                            if (!oldStack.ContainsKey(key)) // 重复的堆栈信息不输出
-                            {
-                                oldStack.Add(key, 1);
-                                message += "\r\n" + stack;
-                                _logger.WriteLog(message);
-                            }
-#endif
-                        }
-                        else // 不包含堆栈信息
-                        {
-                            _logger.WriteLog(message);
-                        }
-                    }
-                    catch (Exception ex) { }
-                }
-            }
-        }
-
-        public override void WriteLine(string message)
-        {
-            Write(message);
-        }
-    }
+using LJLib.Tools.File;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+
+namespace LJLib.LocalLog
+{
+    internal class LocalTraceListener : TraceListener
+    {
+#if !(WindowsCE || PocketPC)
+        private Dictionary<string, byte> oldStack = new Dictionary<string, byte>();
+#endif
+
+        private object _syncRoot = new object();
+
+        private ILogger _logger = null;
+        public bool HasStack { get; set; }
+        public LocalTraceListener(ILogger logger) { _logger = logger; }
+        public override void Write(string message)
+        {
+            lock (_syncRoot)
+            {
+                if (_logger != null)
+                {
+                    try
+                    {
+                        if (HasStack) // 包含堆栈信息
+                        {
+#if !(WindowsCE || PocketPC)
+                            var stack = (new StackTrace()).ToString();
+                            var key = stack;
+                            var index = message.IndexOf(": ");
+                            if (index >= 0)
+                            {
+                                key += message.Substring(0, index);
+                            }
+                            if (!oldStack.ContainsKey(key)) // 重复的堆栈信息不输出
+                            {
+                                oldStack.Add(key, 1);
+                                message += "\r\n" + stack;
+                                _logger.WriteLog(message);
+                            }
+#endif
+                        }
+                        else // 不包含堆栈信息
+                        {
+                            _logger.WriteLog(message);
+                        }
+                    }
+                    catch (Exception ex) { }
+                }
+            }
+        }
+
+        public override void WriteLine(string message)
+        {
+            Write(message);
+        }
+    }
 }

+ 21 - 21
Models/GetFile.cs

@@ -1,21 +1,21 @@
-using LJLib.Net.SPI.Com;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-
-namespace LJProxy.Models
-{
-    public class GetFileRequest : LJRequest
-    {
-        public string Filepath { get; set; }
-        public string token { get; set; }
-        public bool checkAuthorization { get; set; }
-        public DateTime? lastWriteTime { get; set; }
-    }
-
-    public class GetFileResponse : LJResponse
-    {
-        public byte[] FileData { get; set; }
-    }
-}
+using LJLib.Net.SPI.Com;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace LJProxy.Models
+{
+    public class GetFileRequest : LJRequest
+    {
+        public string Filepath { get; set; }
+        public string token { get; set; }
+        public bool checkAuthorization { get; set; }
+        public DateTime? lastWriteTime { get; set; }
+    }
+
+    public class GetFileResponse : LJResponse
+    {
+        public byte[] FileData { get; set; }
+    }
+}

+ 18 - 18
Models/GetProxyDomainList.cs

@@ -1,18 +1,18 @@
-using LJLib.Net.SPI.Com;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Models
-{
-    public class GetProxyDomainListRequest : LJRequest
-    {
-        
-    }
-
-    public class GetProxyDomainListResponse:LJResponse
-    {
-        public List<string> DomainList { get; set; }
-    }
-}
+using LJLib.Net.SPI.Com;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Models
+{
+    public class GetProxyDomainListRequest : LJRequest
+    {
+        
+    }
+
+    public class GetProxyDomainListResponse:LJResponse
+    {
+        public List<string> DomainList { get; set; }
+    }
+}

+ 21 - 21
Models/UploadFiles.cs

@@ -1,21 +1,21 @@
-using LJLib.Net.SPI.Com;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Models
-{
-    public class UploadFilesRequest : LJRequest
-    {
-        public string token { get; set; }
-        public List<FileInfoModel> FileList { get; set; }
-
-    }
-
-    public class FileInfoModel
-    {
-        public string FileName { get; set; }
-        public string FileData { get; set; }
-    }
-}
+using LJLib.Net.SPI.Com;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Models
+{
+    public class UploadFilesRequest : LJRequest
+    {
+        public string token { get; set; }
+        public List<FileInfoModel> FileList { get; set; }
+
+    }
+
+    public class FileInfoModel
+    {
+        public string FileName { get; set; }
+        public string FileData { get; set; }
+    }
+}

+ 34 - 34
Program.cs

@@ -1,34 +1,34 @@
-using LJLib.LocalLog;
-using LJLib.Tools.File;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy
-{
-    public class Program
-    {
-        public static void Main(string[] args)
-        {
-            var binpath = AppContext.BaseDirectory;
-            Trace.AutoFlush = false;
-            Trace.Listeners.Clear();
-            Trace.Listeners.Add(new LocalTraceListener(new SyncLogger(new Logger(binpath, "config.log.txt"))));
-
-            CreateHostBuilder(args).Build().Run();
-        }
-
-        public static IHostBuilder CreateHostBuilder(string[] args) =>
-            Host.CreateDefaultBuilder(args)
-                .ConfigureWebHostDefaults(webBuilder =>
-                {
-                    webBuilder.UseStartup<Startup>();
-                });
-    }
-}
+using LJLib.LocalLog;
+using LJLib.Tools.File;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            var binpath = AppContext.BaseDirectory;
+            Trace.AutoFlush = false;
+            Trace.Listeners.Clear();
+            Trace.Listeners.Add(new LocalTraceListener(new SyncLogger(new Logger(binpath, "config.log.txt"))));
+
+            CreateHostBuilder(args).Build().Run();
+        }
+
+        public static IHostBuilder CreateHostBuilder(string[] args) =>
+            Host.CreateDefaultBuilder(args)
+                .ConfigureWebHostDefaults(webBuilder =>
+                {
+                    webBuilder.UseStartup<Startup>();
+                });
+    }
+}

+ 161 - 117
Providers/L1SvrFileInfo.cs

@@ -1,117 +1,161 @@
-using LJLib.Net.SPI.Client;
-using LJProxy.Models;
-using Microsoft.Extensions.FileProviders;
-using Newtonsoft.Json;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Providers
-{
-    public class L1SvrFileInfo : IFileInfo
-    {
-        private string _fullFilepath;
-        private string _subpath;
-        private FileInfo _file;
-        private FileInfo _tempFile;
-        private MemoryStream _stream;
-        private ILJClient _ljPool;
-        private static object _syncRoot = new object();
-        private string _token;
-        public L1SvrFileInfo(string fullFilepath, string subpath, ILJClient ljPool,string token)
-        {
-            _fullFilepath = fullFilepath;
-            _subpath = subpath;
-            _ljPool = ljPool;
-            _token = token;
-            _stream = new MemoryStream(); ;
-            if (File.Exists(_fullFilepath))
-            {
-                _tempFile = new FileInfo(_fullFilepath);
-                CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime, true);
-            }
-            else
-            {
-                lock (_syncRoot)
-                {
-                    if (File.Exists(_fullFilepath))
-                    {
-                        _tempFile = new FileInfo(_fullFilepath);
-                        CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime,true);
-                    }
-                    else
-                    {
-                        CheckAuthorizationOrGetRemoteFile(null);
-                    }
-
-                }
-            }
-        }
-        public bool Exists => _file!=null;
-
-        public bool IsDirectory => false;
-
-        public DateTimeOffset LastModified => _file.LastWriteTime;
-
-        public long Length => _stream.Length;
-
-        public string Name => _file.Name;
-
-        public string PhysicalPath => _file.FullName;
-
-        public Stream CreateReadStream()
-        {
-            return _stream;
-        }
-
-        public void CheckAuthorizationOrGetRemoteFile(DateTime? lastWriteTime, bool checkAuthorization=false)
-        {
-            var getFileReq = new GetFileRequest() {
-                Filepath = _subpath,
-                token = _token,
-                checkAuthorization = checkAuthorization,
-                lastWriteTime = lastWriteTime
-            };
-            var responseStr = _ljPool.DoExcute(getFileReq.GetApiName(),JsonConvert.SerializeObject(getFileReq));
-            var response = JsonConvert.DeserializeObject<GetFileResponse>(responseStr);
-            if (response.AppErrCode == "900")
-            {
-                if (!checkAuthorization)
-                {
-                    var fileDir = Path.GetDirectoryName(_fullFilepath);
-                    if (!Directory.Exists(fileDir))
-                    {
-                        Directory.CreateDirectory(fileDir);
-                    }
-                    File.WriteAllBytes(_fullFilepath, response.FileData);
-                }
-                else
-                {
-                    if(response.FileData!=null && response.FileData.Length > 0)
-                    {
-                        var fileDir = Path.GetDirectoryName(_fullFilepath);
-                        if (!Directory.Exists(fileDir))
-                        {
-                            Directory.CreateDirectory(fileDir);
-                        }
-                        File.WriteAllBytes(_fullFilepath, response.FileData);
-                    }
-                }
-                _file = new FileInfo(_fullFilepath);
-                byte[] buff = new byte[1024];
-                using(var fs = _file.OpenRead())
-                {
-                    int readCount = fs.Read(buff, 0, buff.Length);
-                    while (readCount > 0)
-                    {
-                        _stream.Write(buff, 0, readCount);
-                        readCount = fs.Read(buff, 0, buff.Length);
-                    }
-                }                
-            }
-        }
-
-    }
-}
+using LJLib.Net.SPI.Client;
+using LJLib.Net.SPI.Com;
+using LJProxy.Models;
+using Microsoft.Extensions.FileProviders;
+using Newtonsoft.Json;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Providers
+{
+    public class L1SvrFileInfo : IFileInfo
+    {
+        private string _fullFilepath;
+        private string _subpath;
+        private FileInfo _file;
+        private FileInfo _tempFile;
+        private MemoryStream _stream;
+        private ILJClient _ljPool;
+        private static object _syncRoot = new object();
+        private string _token;
+        private string annoymousSubpath = "\\anyC84F3B0582994A1184044B116EC2080B\\";
+        public L1SvrFileInfo(string fullFilepath, string subpath, ILJClient ljPool,string token)
+        {
+            _fullFilepath = fullFilepath;
+            _subpath = subpath;
+            _ljPool = ljPool;
+            _token = token;
+            _stream = new MemoryStream(); ;
+            if (File.Exists(_fullFilepath))
+            {
+                _tempFile = new FileInfo(_fullFilepath);
+                if(subpath.IndexOf(annoymousSubpath)>=0)
+                {
+                    _file = _tempFile;
+                    writeFileStream();
+                }
+                else
+                {
+                    CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime, true);
+                }
+            }
+            else
+            {
+                lock (_syncRoot)
+                {
+                    if (File.Exists(_fullFilepath))
+                    {
+                        _tempFile = new FileInfo(_fullFilepath);
+                        CheckAuthorizationOrGetRemoteFile(_tempFile.LastWriteTime,true);
+                    }
+                    else
+                    {
+                        CheckAuthorizationOrGetRemoteFile(null);
+                    }
+
+                }
+            }
+        }
+        public bool Exists => _file!=null;
+
+        public bool IsDirectory => false;
+
+        public DateTimeOffset LastModified => _file.LastWriteTime;
+
+        public long Length => _stream.Length;
+
+        public string Name => _file.Name;
+
+        public string PhysicalPath => _file.FullName;
+
+        public Stream CreateReadStream()
+        {
+            return _stream;
+        }
+
+        public void CheckAuthorizationOrGetRemoteFile(DateTime? lastWriteTime, bool checkAuthorization=false)
+        {
+            try
+            {
+                var getFileReq = new GetFileRequest()
+                {
+                    Filepath = _subpath,
+                    token = _token,
+                    checkAuthorization = checkAuthorization,
+                    lastWriteTime = lastWriteTime
+                };
+
+                Stopwatch sw = Stopwatch.StartNew();
+                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:request GetFileRequest");
+                var responseStr = _ljPool.DoExcute(getFileReq.GetApiName(), JsonConvert.SerializeObject(getFileReq));
+                Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}:response GetFileRequest");
+                Console.WriteLine($"GetFileRequest ellapsed:{sw.ElapsedMilliseconds} ms");
+                sw.Restart();
+                var response = JsonConvert.DeserializeObject<GetFileResponse>(responseStr);
+                Console.WriteLine($"DeserializeObject ellapsed:{sw.ElapsedMilliseconds} ms");
+                Console.WriteLine(response.AppErrCode+":"+ response.AppErrMsg);
+                sw.Restart();
+                if (response.AppErrCode == "900")
+                {
+                    if (!checkAuthorization)
+                    {
+                        var fileDir = Path.GetDirectoryName(_fullFilepath);
+                        if (!Directory.Exists(fileDir))
+                        {
+                            Directory.CreateDirectory(fileDir);
+                        }
+                        File.WriteAllBytes(_fullFilepath, response.FileData);
+                    }
+                    else
+                    {
+                        if (response.FileData != null && response.FileData.Length > 0)
+                        {
+                            var fileDir = Path.GetDirectoryName(_fullFilepath);
+                            if (!Directory.Exists(fileDir))
+                            {
+                                Directory.CreateDirectory(fileDir);
+                            }
+                            File.WriteAllBytes(_fullFilepath, response.FileData);
+                        }
+                    }
+                    Console.WriteLine($"WriteAllBytes ellapsed:{sw.ElapsedMilliseconds} ms");
+                    sw.Restart();
+                    _file = new FileInfo(_fullFilepath);
+                    writeFileStream();
+                    Console.WriteLine($"OpenRead ellapsed:{sw.ElapsedMilliseconds} ms");
+                }
+            }catch(Exception ex)
+            {
+                Trace.WriteLine($"CheckAuthorizationOrGetRemoteFile:{ex}");
+                Console.WriteLine($"CheckAuthorizationOrGetRemoteFile:{ex}");
+            }
+        }
+
+        public void writeFileStream()
+        {
+            try
+            {
+                if (_file == null) return;
+                byte[] buff = new byte[1024];
+                using (var fs = _file.OpenRead())
+                {
+                    int readCount = fs.Read(buff, 0, buff.Length);
+                    while (readCount > 0)
+                    {
+                        _stream.Write(buff, 0, readCount);
+                        readCount = fs.Read(buff, 0, buff.Length);
+                    }
+                }
+            }catch(Exception ex)
+            {
+                Trace.WriteLine($"writeFileStream:{ex}");
+                Console.WriteLine($"writeFileStream:{ex}");
+            }
+        }
+
+    }
+}

+ 58 - 56
Providers/L1SvrFileProvider.cs

@@ -1,56 +1,58 @@
-using LJProxy.Services;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.FileProviders;
-using Microsoft.Extensions.Primitives;
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Providers
-{
-    public class L1SvrFileProvider : IFileProvider
-    {
-        private string _contentRoot;
-        private LJClientPoolService _ljClient;
-        private string _token;
-        IHttpContextAccessor _accessor;
-        public L1SvrFileProvider(string contentRoot, LJClientPoolService ljClient,IHttpContextAccessor accessor)
-        {
-            _contentRoot = contentRoot;
-            _ljClient = ljClient;
-            _accessor = accessor;
-        }
-
-        public IDirectoryContents GetDirectoryContents(string subpath)
-        {
-            throw new NotImplementedException();
-        }
-
-        public IFileInfo GetFileInfo(string subpath)
-        {
-            string physicSubpath = subpath.Replace("/","\\");
-            int suffixIndex = physicSubpath.IndexOf(DocumentSuffix);
-            if (suffixIndex > 0)
-            {
-                string fileExtension = Path.GetExtension(physicSubpath);
-                physicSubpath = physicSubpath.Substring(0, suffixIndex);
-                physicSubpath = physicSubpath + fileExtension;
-            }
-            string directory = @$"{_contentRoot}\wwwroot";
-            var fullFilepath = @$"{directory}{physicSubpath}";
-            _token = _accessor.HttpContext.Request.Headers["Authorization"];
-            var result = new L1SvrFileInfo(fullFilepath, physicSubpath,_ljClient.Pool,_token);
-            return result;
-        }
-
-        private readonly static string DocumentSuffix = "$27BAljSuffix!";
-
-
-        public IChangeToken Watch(string filter)
-        {
-            throw new NotImplementedException();
-        }
-    }
-}
+using LJProxy.Services;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.FileProviders;
+using Microsoft.Extensions.Primitives;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Web;
+
+namespace LJProxy.Providers
+{
+    public class L1SvrFileProvider : IFileProvider
+    {
+        private string _contentRoot;
+        private LJClientPoolService _ljClient;
+        private string _token;
+        IHttpContextAccessor _accessor;
+        public L1SvrFileProvider(string contentRoot, LJClientPoolService ljClient,IHttpContextAccessor accessor)
+        {
+            _contentRoot = contentRoot;
+            _ljClient = ljClient;
+            _accessor = accessor;
+        }
+
+        public IDirectoryContents GetDirectoryContents(string subpath)
+        {
+            throw new NotImplementedException();
+        }
+
+        public IFileInfo GetFileInfo(string subpath)
+        {
+            string physicSubpath = subpath.Replace("/","\\");
+            int suffixIndex = physicSubpath.IndexOf(DocumentSuffix);
+            if (suffixIndex > 0)
+            {
+                string fileExtension = Path.GetExtension(physicSubpath);
+                physicSubpath = physicSubpath.Substring(0, suffixIndex);
+                physicSubpath = physicSubpath + fileExtension;
+            }
+            physicSubpath = HttpUtility.UrlDecode(physicSubpath);
+            string directory = @$"{_contentRoot}\wwwroot";
+            var fullFilepath = @$"{directory}{physicSubpath}";
+            _token = _accessor.HttpContext.Request.Headers["Authorization"];
+            var result = new L1SvrFileInfo(fullFilepath, physicSubpath,_ljClient.Pool,_token);
+            return result;
+        }
+
+        private readonly static string DocumentSuffix = "$27BAljSuffix!";
+
+
+        public IChangeToken Watch(string filter)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 33 - 33
Services/LJClientPoolService.cs

@@ -1,33 +1,33 @@
-using LJLib.Client;
-using LJLib.Net.SPI.Client;
-using LJProxy.Settings;
-using Microsoft.Extensions.Options;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Services
-{
-    public class LJClientPoolService
-    {
-        private AppSettings _appSettingModel;
-        private ILJClient _pool;
-        public LJClientPoolService(IOptions<AppSettings> appSettingModel)
-        {
-            _appSettingModel = appSettingModel.Value;
-            var url = _appSettingModel.L1SvrUrl;
-            var urlArr = url.Split(':');
-            var ip = urlArr[0];
-            var port = urlArr[1];
-            var creator = new DirectP1ClientCreator(ip, Convert.ToInt32(port));
-            _pool = new LJClientPool(creator, _appSettingModel.ThreadSize);
-        }
-
-        public ILJClient Pool
-        {
-            get { return _pool; }
-        }
-
-    }
-}
+using LJLib.Client;
+using LJLib.Net.SPI.Client;
+using LJProxy.Settings;
+using Microsoft.Extensions.Options;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Services
+{
+    public class LJClientPoolService
+    {
+        private AppSettings _appSettingModel;
+        private ILJClient _pool;
+        public LJClientPoolService(IOptions<AppSettings> appSettingModel)
+        {
+            _appSettingModel = appSettingModel.Value;
+            var url = _appSettingModel.L1SvrUrl;
+            var urlArr = url.Split(':');
+            var ip = urlArr[0];
+            var port = urlArr[1];
+            var creator = new DirectP1ClientCreator(ip, Convert.ToInt32(port));
+            _pool = new LJClientPool(creator, _appSettingModel.ThreadSize);
+        }
+
+        public ILJClient Pool
+        {
+            get { return _pool; }
+        }
+
+    }
+}

+ 11 - 11
Services/ServiceBase.cs

@@ -1,11 +1,11 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Services
-{
-    public abstract class ServiceBase
-    {
-    }
-}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Services
+{
+    public abstract class ServiceBase
+    {
+    }
+}

+ 71 - 71
Services/VersionService.cs

@@ -1,71 +1,71 @@
-using Newtonsoft.Json.Linq;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
-
-namespace LJProxy.Services
-{
-    public class VersionService:ServiceBase
-    {
-        private static object _updateJsonSyncRoot = new object();
-        private static object _apkSyncRoot = new object();
-
-        public string GetUpdateJson()
-        {
-            string updateJson = string.Empty;
-            string key = "UpdateJson";
-            lock (_updateJsonSyncRoot)
-            {
-                updateJson = Cache.DefaultCache.Get(key) as string;
-                if (string.IsNullOrEmpty(updateJson))
-                {
-                    string updateJsonPath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\update.json";
-                    updateJson = System.IO.File.ReadAllText(updateJsonPath, Encoding.UTF8);
-                    Cache.DefaultCache.Add(key, updateJson, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { updateJsonPath }));
-                }
-            }
-            return updateJson;
-        }
-
-
-        public byte[] GetAPK(string apkName)
-        {
-            if (string.IsNullOrEmpty(apkName)) return null;
-            var updateJson = GetUpdateJson();
-            var updateInfoObj = JObject.Parse(updateJson);
-            string url = updateInfoObj["url"]?.ToString();
-            if (string.IsNullOrEmpty(url))
-            {
-                return null;
-            }
-            Regex regx = new Regex(@"GetAppUpdate/(?<apkName>.*?\.apk)", RegexOptions.IgnoreCase);
-            var matchResult = regx.Match(url);
-            if (matchResult.Success)
-            {
-                var jsonApkName = matchResult.Groups["apkName"]?.Value;
-                if (!apkName.Equals(jsonApkName, StringComparison.OrdinalIgnoreCase)) return null;
-                string key = apkName.ToLower();
-                byte[] result = null;
-                lock (_apkSyncRoot)
-                {
-                    result = Cache.DefaultCache.Get(key) as byte[];
-                    if (result == null)
-                    {
-                        string apkFilePath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\{apkName}";
-                        if (!System.IO.File.Exists(apkFilePath))
-                        {
-                            return null;
-                        }
-                        result = System.IO.File.ReadAllBytes(apkFilePath);
-                        Cache.DefaultCache.Add(key, result, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { apkFilePath }));
-                    }
-                }
-                return result;
-            }
-            return null;
-        }
-    }
-}
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace LJProxy.Services
+{
+    public class VersionService:ServiceBase
+    {
+        private static object _updateJsonSyncRoot = new object();
+        private static object _apkSyncRoot = new object();
+
+        public string GetUpdateJson()
+        {
+            string updateJson = string.Empty;
+            string key = "UpdateJson";
+            lock (_updateJsonSyncRoot)
+            {
+                updateJson = Cache.DefaultCache.Get(key) as string;
+                if (string.IsNullOrEmpty(updateJson))
+                {
+                    string updateJsonPath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\update.json";
+                    updateJson = System.IO.File.ReadAllText(updateJsonPath, Encoding.UTF8);
+                    Cache.DefaultCache.Add(key, updateJson, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { updateJsonPath }));
+                }
+            }
+            return updateJson;
+        }
+
+
+        public byte[] GetAPK(string apkName)
+        {
+            if (string.IsNullOrEmpty(apkName)) return null;
+            var updateJson = GetUpdateJson();
+            var updateInfoObj = JObject.Parse(updateJson);
+            string url = updateInfoObj["url"]?.ToString();
+            if (string.IsNullOrEmpty(url))
+            {
+                return null;
+            }
+            Regex regx = new Regex(@"GetAppUpdate/(?<apkName>.*?\.apk)", RegexOptions.IgnoreCase);
+            var matchResult = regx.Match(url);
+            if (matchResult.Success)
+            {
+                var jsonApkName = matchResult.Groups["apkName"]?.Value;
+                if (!apkName.Equals(jsonApkName, StringComparison.OrdinalIgnoreCase)) return null;
+                string key = apkName.ToLower();
+                byte[] result = null;
+                lock (_apkSyncRoot)
+                {
+                    result = Cache.DefaultCache.Get(key) as byte[];
+                    if (result == null)
+                    {
+                        string apkFilePath = @$"{AppDomain.CurrentDomain.BaseDirectory}apk\{apkName}";
+                        if (!System.IO.File.Exists(apkFilePath))
+                        {
+                            return null;
+                        }
+                        result = System.IO.File.ReadAllBytes(apkFilePath);
+                        Cache.DefaultCache.Add(key, result, Cache.CreateCacheItemPolicy(null, DateTime.Now.AddMinutes(30), new List<string>() { apkFilePath }));
+                    }
+                }
+                return result;
+            }
+            return null;
+        }
+    }
+}

+ 14 - 14
Settings/AppSettings.cs

@@ -1,14 +1,14 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy.Settings
-{
-    public class AppSettings
-    {
-        public string L1SvrUrl { get; set; }
-        public int ThreadSize { get; set; }
-        public List<string> ProxyDomainList { get; set; }
-    }
-}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy.Settings
+{
+    public class AppSettings
+    {
+        public string L1SvrUrl { get; set; }
+        public int ThreadSize { get; set; }
+        public List<string> ProxyDomainList { get; set; }
+    }
+}

+ 78 - 78
Startup.cs

@@ -1,78 +1,78 @@
-using LJProxy.Providers;
-using LJProxy.Services;
-using LJProxy.Settings;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.AspNetCore.Http.Features;
-using Microsoft.AspNetCore.HttpsPolicy;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.AspNetCore.StaticFiles;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace LJProxy
-{
-    public class Startup
-    {
-        public Startup(IConfiguration configuration)
-        {
-            Configuration = configuration;
-        }
-
-        public IConfiguration Configuration { get; }
-
-        // This method gets called by the runtime. Use this method to add services to the container.
-        public void ConfigureServices(IServiceCollection services)
-        {
-            services.AddControllers().AddNewtonsoftJson(opt => {
-                //opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
-            });
-            services.Configure<AppSettings>(Configuration.GetSection("Appsettings"));
-            services.AddSingleton<LJClientPoolService>();
-            services.AddScoped<VersionService>();
-            GlobalVar.InitSetting(Configuration.GetSection("Appsettings"));
-            services.AddHttpClient();
-            services.Configure<FormOptions>(opt => {
-            //    opt.ValueLengthLimit = 20 * 1024 * 1024;
-            //    opt.MultipartBodyLengthLimit = 20* 1024 * 1024;
-            //    opt.MultipartHeadersCountLimit = 5;
-            });
-            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
-        }
-
-        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
-        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
-        {
-            if (env.IsDevelopment())
-            {
-                app.UseDeveloperExceptionPage();
-            }
-
-            app.UseHttpsRedirection();
-
-            app.UseRouting();
-
-            app.UseAuthorization();
-
-            app.UseEndpoints(endpoints =>
-            {
-                endpoints.MapControllers();
-            });
-
-            app.UseDefaultFiles();
-            var provider = new FileExtensionContentTypeProvider();
-            provider.Mappings[".apk"] = "application/vnd.android.package-archive";
-            app.UseStaticFiles(new StaticFileOptions { 
-                FileProvider = new L1SvrFileProvider(env.ContentRootPath,app.ApplicationServices.GetService<LJClientPoolService>(),app.ApplicationServices.GetService<IHttpContextAccessor>()),
-                ContentTypeProvider = provider
-            });
-        }
-    }
-}
+using LJProxy.Providers;
+using LJProxy.Services;
+using LJProxy.Settings;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
+using Microsoft.AspNetCore.HttpsPolicy;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.StaticFiles;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace LJProxy
+{
+    public class Startup
+    {
+        public Startup(IConfiguration configuration)
+        {
+            Configuration = configuration;
+        }
+
+        public IConfiguration Configuration { get; }
+
+        // This method gets called by the runtime. Use this method to add services to the container.
+        public void ConfigureServices(IServiceCollection services)
+        {
+            services.AddControllers().AddNewtonsoftJson(opt => {
+                //opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
+            });
+            services.Configure<AppSettings>(Configuration.GetSection("Appsettings"));
+            services.AddSingleton<LJClientPoolService>();
+            services.AddScoped<VersionService>();
+            GlobalVar.InitSetting(Configuration.GetSection("Appsettings"));
+            services.AddHttpClient();
+            services.Configure<FormOptions>(opt => {
+            //    opt.ValueLengthLimit = 20 * 1024 * 1024;
+            //    opt.MultipartBodyLengthLimit = 20* 1024 * 1024;
+            //    opt.MultipartHeadersCountLimit = 5;
+            });
+            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
+        }
+
+        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+        {
+            if (env.IsDevelopment())
+            {
+                app.UseDeveloperExceptionPage();
+            }
+
+            app.UseHttpsRedirection();
+
+            app.UseRouting();
+
+            app.UseAuthorization();
+
+            app.UseEndpoints(endpoints =>
+            {
+                endpoints.MapControllers();
+            });
+
+            app.UseDefaultFiles();
+            var provider = new FileExtensionContentTypeProvider();
+            provider.Mappings[".apk"] = "application/vnd.android.package-archive";
+            app.UseStaticFiles(new StaticFileOptions { 
+                FileProvider = new L1SvrFileProvider(env.ContentRootPath,app.ApplicationServices.GetService<LJClientPoolService>(),app.ApplicationServices.GetService<IHttpContextAccessor>()),
+                ContentTypeProvider = provider
+            });
+        }
+    }
+}

+ 43 - 43
StreamHelper/StreamHelper.cs

@@ -1,43 +1,43 @@
-using System;
-using System.IO;
-using System.Threading;
-
-namespace LJLib.Tools.Helper
-{
-    public class StreamHelper
-    {
-        public static void StreamCopy(Stream dest, Stream source, int len)
-        {
-            byte[] buff = new byte[10240];
-            int total = 0;
-            while (total < len)
-            {
-                var read = source.Read(buff, 0, Math.Min(buff.Length, len - total));
-                if (read > 0)
-                {
-                    dest.Write(buff, 0, read);
-                    dest.Flush();
-                    total += read;
-                }
-                else
-                {
-                    Thread.Sleep(100);
-                }
-            }
-        }
-
-        public static void StreamCopy(Stream dest, Stream source)
-        {
-            byte[] buff = new byte[10240];
-            int read = 0;
-            int total = 0;
-            while ((read = source.Read(buff, 0, buff.Length)) > 0)
-            {
-                dest.Write(buff, 0, read);
-                dest.Flush();
-                total += read;
-            }
-        }
-
-    }
-}
+using System;
+using System.IO;
+using System.Threading;
+
+namespace LJLib.Tools.Helper
+{
+    public class StreamHelper
+    {
+        public static void StreamCopy(Stream dest, Stream source, int len)
+        {
+            byte[] buff = new byte[10240];
+            int total = 0;
+            while (total < len)
+            {
+                var read = source.Read(buff, 0, Math.Min(buff.Length, len - total));
+                if (read > 0)
+                {
+                    dest.Write(buff, 0, read);
+                    dest.Flush();
+                    total += read;
+                }
+                else
+                {
+                    Thread.Sleep(100);
+                }
+            }
+        }
+
+        public static void StreamCopy(Stream dest, Stream source)
+        {
+            byte[] buff = new byte[10240];
+            int read = 0;
+            int total = 0;
+            while ((read = source.Read(buff, 0, buff.Length)) > 0)
+            {
+                dest.Write(buff, 0, read);
+                dest.Flush();
+                total += read;
+            }
+        }
+
+    }
+}

+ 8 - 8
TextLog/ILogger.cs

@@ -1,8 +1,8 @@
-
-namespace LJLib.Tools.File
-{
-    internal interface ILogger
-    {
-        void WriteLog(string msg);
-    }
-}
+
+namespace LJLib.Tools.File
+{
+    internal interface ILogger
+    {
+        void WriteLog(string msg);
+    }
+}

+ 135 - 135
TextLog/Logger.cs

@@ -1,135 +1,135 @@
-using System;
-using System.IO;
-using System.Reflection;
-
-namespace LJLib.Tools.File
-{
-    internal class Logger : ILogger
-    {
-        private string _path;
-
-        private string _filename = "log.txt";
-
-        private object _syncRoot = new object();
-
-        public Logger()
-        {
-            _path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
-        }
-
-        public Logger(string path)
-        {
-            _path = path;
-        }
-
-        public Logger(string path, string filename)
-        {
-            _path = path;
-            _filename = filename;
-        }
-
-        public virtual string Path
-        {
-            get { return _path; }
-        }
-
-        public virtual string FileName
-        {
-            get { return _filename; }
-            set { _filename = value; }
-        }
-
-        public virtual string FullName
-        {
-            get { return _path + "\\" + _filename; }
-        }
-
-        public virtual void WriteLog(string msg)
-        {
-            try
-            {
-                FileInfo file = new FileInfo(FullName);
-                if (file.Exists && file.Length > 10240000)
-                {
-                    string tmpfile = FullName + ".tmp";
-                    using (FileStream fs = file.Open(FileMode.Open, FileAccess.Read))
-                    using (StreamReader reader = new StreamReader(fs))
-                    {
-                        fs.Seek(-1024000, SeekOrigin.End);
-                        reader.ReadLine();
-                        using (StreamWriter sw = System.IO.File.AppendText(tmpfile))
-                        {
-                            while (!reader.EndOfStream)
-                            {
-                                string strline = reader.ReadLine();
-                                sw.WriteLine(strline);
-                            }
-                            sw.Flush();
-                            sw.Close();
-                        }
-                    }
-                    file.Delete();
-                    System.IO.File.Move(tmpfile, FullName);
-                }
-
-                using (StreamWriter sw = System.IO.File.AppendText(FullName))
-                {
-                    string rslt = "//====================================================================\r\n";
-                    rslt += "// 时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
-                    rslt += "//--------------------------------------------------------------------\r\n";
-                    rslt += "// " + msg.Replace("\r\n", "\r\n// ") + "\r\n";
-                    rslt += "//====================================================================\r\n\r\n";
-                    sw.Write(rslt);
-                    sw.Flush();
-                    sw.Close();
-                }
-            }
-            catch (System.Exception ex)
-            {
-            	
-            }
-        }
-
-        public virtual void InsertLog(string msg)
-        {
-            try
-            {
-                using (FileStream fs = System.IO.File.Open(FullName, FileMode.OpenOrCreate))
-                {
-                    StreamReader reader = new StreamReader(fs);
-                    string filestr = reader.ReadToEnd();
-                    filestr = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " " + msg + "\r\n" + filestr;
-                    fs.Seek(0, SeekOrigin.Begin);
-                    StreamWriter writer = new StreamWriter(fs);
-                    writer.Write(filestr);
-                    writer.Flush();
-                }
-            }
-            catch (System.Exception ex)
-            {
-            	
-            }
-        }
-
-        public virtual bool IsSynchronized
-        {
-            get
-            {
-                return false;
-            }
-        }
-
-        public virtual object SyncRoot
-        {
-            get
-            {
-                return _syncRoot;
-            }
-        }
-
-        public static Logger Synchronized(Logger logger)
-        {
-            return new SyncLogger(logger);
-        }
-    }
-}
+using System;
+using System.IO;
+using System.Reflection;
+
+namespace LJLib.Tools.File
+{
+    internal class Logger : ILogger
+    {
+        private string _path;
+
+        private string _filename = "log.txt";
+
+        private object _syncRoot = new object();
+
+        public Logger()
+        {
+            _path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
+        }
+
+        public Logger(string path)
+        {
+            _path = path;
+        }
+
+        public Logger(string path, string filename)
+        {
+            _path = path;
+            _filename = filename;
+        }
+
+        public virtual string Path
+        {
+            get { return _path; }
+        }
+
+        public virtual string FileName
+        {
+            get { return _filename; }
+            set { _filename = value; }
+        }
+
+        public virtual string FullName
+        {
+            get { return _path + "\\" + _filename; }
+        }
+
+        public virtual void WriteLog(string msg)
+        {
+            try
+            {
+                FileInfo file = new FileInfo(FullName);
+                if (file.Exists && file.Length > 10240000)
+                {
+                    string tmpfile = FullName + ".tmp";
+                    using (FileStream fs = file.Open(FileMode.Open, FileAccess.Read))
+                    using (StreamReader reader = new StreamReader(fs))
+                    {
+                        fs.Seek(-1024000, SeekOrigin.End);
+                        reader.ReadLine();
+                        using (StreamWriter sw = System.IO.File.AppendText(tmpfile))
+                        {
+                            while (!reader.EndOfStream)
+                            {
+                                string strline = reader.ReadLine();
+                                sw.WriteLine(strline);
+                            }
+                            sw.Flush();
+                            sw.Close();
+                        }
+                    }
+                    file.Delete();
+                    System.IO.File.Move(tmpfile, FullName);
+                }
+
+                using (StreamWriter sw = System.IO.File.AppendText(FullName))
+                {
+                    string rslt = "//====================================================================\r\n";
+                    rslt += "// 时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n";
+                    rslt += "//--------------------------------------------------------------------\r\n";
+                    rslt += "// " + msg.Replace("\r\n", "\r\n// ") + "\r\n";
+                    rslt += "//====================================================================\r\n\r\n";
+                    sw.Write(rslt);
+                    sw.Flush();
+                    sw.Close();
+                }
+            }
+            catch (System.Exception ex)
+            {
+            	
+            }
+        }
+
+        public virtual void InsertLog(string msg)
+        {
+            try
+            {
+                using (FileStream fs = System.IO.File.Open(FullName, FileMode.OpenOrCreate))
+                {
+                    StreamReader reader = new StreamReader(fs);
+                    string filestr = reader.ReadToEnd();
+                    filestr = DateTime.Now.ToString("yyyy-MM-dd HH:mm") + " " + msg + "\r\n" + filestr;
+                    fs.Seek(0, SeekOrigin.Begin);
+                    StreamWriter writer = new StreamWriter(fs);
+                    writer.Write(filestr);
+                    writer.Flush();
+                }
+            }
+            catch (System.Exception ex)
+            {
+            	
+            }
+        }
+
+        public virtual bool IsSynchronized
+        {
+            get
+            {
+                return false;
+            }
+        }
+
+        public virtual object SyncRoot
+        {
+            get
+            {
+                return _syncRoot;
+            }
+        }
+
+        public static Logger Synchronized(Logger logger)
+        {
+            return new SyncLogger(logger);
+        }
+    }
+}

+ 69 - 69
TextLog/SyncLogger.cs

@@ -1,69 +1,69 @@
-
-namespace LJLib.Tools.File
-{
-    internal class SyncLogger : Logger
-    {
-        protected Logger _logger;
-
-        public SyncLogger(Logger logger)
-        {
-            _logger = logger;
-        }
-
-        public override string Path
-        {
-            get
-            {
-                return _logger.Path;
-            }
-        }
-
-        public override string FileName
-        {
-            get
-            {
-                return _logger.FileName;
-            }
-        }
-
-        public override string FullName
-        {
-            get
-            {
-                return _logger.FullName;
-            }
-        }
-
-        public override void WriteLog(string msg)
-        {
-            lock (_logger.SyncRoot)
-            {
-                _logger.WriteLog(msg);
-            }
-        }
-
-        public override void InsertLog(string msg)
-        {
-            lock (_logger.SyncRoot)
-            {
-                _logger.InsertLog(msg);
-            }
-        }
-
-        public override bool IsSynchronized
-        {
-            get
-            {
-                return true;
-            }
-        }
-
-        public override object SyncRoot
-        {
-            get
-            {
-                return _logger.SyncRoot;
-            }
-        }
-    }
-}
+
+namespace LJLib.Tools.File
+{
+    internal class SyncLogger : Logger
+    {
+        protected Logger _logger;
+
+        public SyncLogger(Logger logger)
+        {
+            _logger = logger;
+        }
+
+        public override string Path
+        {
+            get
+            {
+                return _logger.Path;
+            }
+        }
+
+        public override string FileName
+        {
+            get
+            {
+                return _logger.FileName;
+            }
+        }
+
+        public override string FullName
+        {
+            get
+            {
+                return _logger.FullName;
+            }
+        }
+
+        public override void WriteLog(string msg)
+        {
+            lock (_logger.SyncRoot)
+            {
+                _logger.WriteLog(msg);
+            }
+        }
+
+        public override void InsertLog(string msg)
+        {
+            lock (_logger.SyncRoot)
+            {
+                _logger.InsertLog(msg);
+            }
+        }
+
+        public override bool IsSynchronized
+        {
+            get
+            {
+                return true;
+            }
+        }
+
+        public override object SyncRoot
+        {
+            get
+            {
+                return _logger.SyncRoot;
+            }
+        }
+    }
+}

+ 78 - 78
Utilities/APKHelper.cs

@@ -1,78 +1,78 @@
-using AndroidXml;
-using ICSharpCode.SharpZipLib.Zip;
-using LJLib.Tools.Helper;
-using System.IO;
-using System.Xml;
-
-namespace LJLib
-{
-    public class APKHelper
-    {
-        public string GetVersionName(string apkPath)
-        {
-            using (var fs = new FileStream(apkPath, FileMode.Open, FileAccess.Read))
-            {
-                return GetVersionName(fs);
-            }
-        }
-
-        public string GetVersionName(byte[] apkbytes)
-        {
-            using (var fs = new MemoryStream(apkbytes))
-            {
-                return GetVersionName(fs);
-            }
-        }
-
-        public string GetVersionName(Stream apkStream)
-        {
-            byte[] xmlbytes;
-
-            using (var zipfile = new ZipFile(apkStream))
-            {
-                var item = zipfile.GetEntry("AndroidManifest.xml");
-                using (var ms = new MemoryStream())
-                using (var strm = zipfile.GetInputStream(item))
-                {
-                    StreamHelper.StreamCopy(ms, strm);
-                    xmlbytes = ms.ToArray();
-                }
-            }
-
-            using (var ms = new MemoryStream(xmlbytes))
-            {
-                XmlReader reader;
-                if (xmlbytes[0] == '<' || char.IsWhiteSpace((char) xmlbytes[0]))
-                {
-                    // Normal XML file
-                    reader = new XmlTextReader(ms)
-                    {
-                        WhitespaceHandling = WhitespaceHandling.None
-                    };
-                }
-                else
-                {
-                    // Android binary XML
-                    reader = new AndroidXmlReader(ms);
-                }
-                using (reader)
-                while (reader.Read())
-                {
-                    if (reader.NodeType == XmlNodeType.Element && reader.Name.ToLower() == "manifest")
-                    {
-                        for (int i = 0; i < reader.AttributeCount; i++)
-                        {
-                            reader.MoveToAttribute(i);
-                            if (reader.LocalName.ToLower() == "versionname")
-                            {
-                                return reader.Value;
-                            }
-                        }
-                        reader.MoveToElement();
-                    }
-                }
-                return string.Empty;
-            }
-        }
-    }
-}
+using AndroidXml;
+using ICSharpCode.SharpZipLib.Zip;
+using LJLib.Tools.Helper;
+using System.IO;
+using System.Xml;
+
+namespace LJLib
+{
+    public class APKHelper
+    {
+        public string GetVersionName(string apkPath)
+        {
+            using (var fs = new FileStream(apkPath, FileMode.Open, FileAccess.Read))
+            {
+                return GetVersionName(fs);
+            }
+        }
+
+        public string GetVersionName(byte[] apkbytes)
+        {
+            using (var fs = new MemoryStream(apkbytes))
+            {
+                return GetVersionName(fs);
+            }
+        }
+
+        public string GetVersionName(Stream apkStream)
+        {
+            byte[] xmlbytes;
+
+            using (var zipfile = new ZipFile(apkStream))
+            {
+                var item = zipfile.GetEntry("AndroidManifest.xml");
+                using (var ms = new MemoryStream())
+                using (var strm = zipfile.GetInputStream(item))
+                {
+                    StreamHelper.StreamCopy(ms, strm);
+                    xmlbytes = ms.ToArray();
+                }
+            }
+
+            using (var ms = new MemoryStream(xmlbytes))
+            {
+                XmlReader reader;
+                if (xmlbytes[0] == '<' || char.IsWhiteSpace((char) xmlbytes[0]))
+                {
+                    // Normal XML file
+                    reader = new XmlTextReader(ms)
+                    {
+                        WhitespaceHandling = WhitespaceHandling.None
+                    };
+                }
+                else
+                {
+                    // Android binary XML
+                    reader = new AndroidXmlReader(ms);
+                }
+                using (reader)
+                while (reader.Read())
+                {
+                    if (reader.NodeType == XmlNodeType.Element && reader.Name.ToLower() == "manifest")
+                    {
+                        for (int i = 0; i < reader.AttributeCount; i++)
+                        {
+                            reader.MoveToAttribute(i);
+                            if (reader.LocalName.ToLower() == "versionname")
+                            {
+                                return reader.Value;
+                            }
+                        }
+                        reader.MoveToElement();
+                    }
+                }
+                return string.Empty;
+            }
+        }
+    }
+}

+ 64 - 64
Utilities/MD5.cs

@@ -1,64 +1,64 @@
-using System;
-using System.IO;
-
-namespace LJLib.Tools.Encry
-{
-    public class MD5
-    {
-        public byte[] ComputeHash(byte[] bytes)
-        {
-            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
-            {
-                return md5.ComputeHash(bytes);
-            }
-        }
-
-        public byte[] ComputeHash(byte[] bytes, int offset, int count)
-        {
-            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
-            {
-                return md5.ComputeHash(bytes, offset, count);
-            }
-        }
-
-        public byte[] ComputeHash(System.IO.Stream inputStream)
-        {
-            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
-            {
-                return md5.ComputeHash(inputStream);
-            }
-        }
-
-        public string GetMD5(byte[] bytes)
-        {
-                byte[] rslt = this.ComputeHash(bytes);
-                string str_rslt = BitConverter.ToString(rslt);
-                str_rslt = str_rslt.Replace("-", "");
-                return str_rslt;
-        }
-
-        public string GetMD5(byte[] bytes, int offset, int count)
-        {
-                byte[] rslt = this.ComputeHash(bytes, offset, count);
-                string str_rslt = BitConverter.ToString(rslt);
-                str_rslt = str_rslt.Replace("-", "");
-                return str_rslt;
-        }
-
-        public string GetMD5(System.IO.Stream inputStream)
-        {
-            byte[] rslt = this.ComputeHash(inputStream);
-            string str_rslt = BitConverter.ToString(rslt);
-            str_rslt = str_rslt.Replace("-", "");
-            return str_rslt;
-        }
-
-        public string GetMD5(string filename)
-        {
-            using (var fs = System.IO.File.OpenRead(filename))
-            {
-                return GetMD5(fs);
-            }
-        }
-    }
-}
+using System;
+using System.IO;
+
+namespace LJLib.Tools.Encry
+{
+    public class MD5
+    {
+        public byte[] ComputeHash(byte[] bytes)
+        {
+            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
+            {
+                return md5.ComputeHash(bytes);
+            }
+        }
+
+        public byte[] ComputeHash(byte[] bytes, int offset, int count)
+        {
+            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
+            {
+                return md5.ComputeHash(bytes, offset, count);
+            }
+        }
+
+        public byte[] ComputeHash(System.IO.Stream inputStream)
+        {
+            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
+            {
+                return md5.ComputeHash(inputStream);
+            }
+        }
+
+        public string GetMD5(byte[] bytes)
+        {
+                byte[] rslt = this.ComputeHash(bytes);
+                string str_rslt = BitConverter.ToString(rslt);
+                str_rslt = str_rslt.Replace("-", "");
+                return str_rslt;
+        }
+
+        public string GetMD5(byte[] bytes, int offset, int count)
+        {
+                byte[] rslt = this.ComputeHash(bytes, offset, count);
+                string str_rslt = BitConverter.ToString(rslt);
+                str_rslt = str_rslt.Replace("-", "");
+                return str_rslt;
+        }
+
+        public string GetMD5(System.IO.Stream inputStream)
+        {
+            byte[] rslt = this.ComputeHash(inputStream);
+            string str_rslt = BitConverter.ToString(rslt);
+            str_rslt = str_rslt.Replace("-", "");
+            return str_rslt;
+        }
+
+        public string GetMD5(string filename)
+        {
+            using (var fs = System.IO.File.OpenRead(filename))
+            {
+                return GetMD5(fs);
+            }
+        }
+    }
+}

+ 9 - 9
appsettings.Development.json

@@ -1,9 +1,9 @@
-{
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
-    }
-  }
-}
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  }
+}

+ 15 - 15
appsettings.json

@@ -1,15 +1,15 @@
-{
-  "Appsettings": {
-    "L1SvrUrl": "127.0.0.1:30032",
-    "ThreadSize": 20,
-    "ProxyDomainList": ["192.168.0.94","l1mes.futuralimited.com"]
-  },
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft": "Warning",
-      "Microsoft.Hosting.Lifetime": "Information"
-    }
-  },
-  "AllowedHosts": "*"
-}
+{
+  "Appsettings": {
+    "L1SvrUrl": "127.0.0.1:30032",
+    "ThreadSize": 20,
+    "ProxyDomainList": ["192.168.0.94","l1mes.futuralimited.com"]
+  },
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  },
+  "AllowedHosts": "*"
+}

+ 31 - 0
wwwroot/anyC84F3B0582994A1184044B116EC2080B/index.html

@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<html>
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="maximum-scale=1.0, minimum-scale=1.0, user-scalable=0, initial-scale=1.0, width=device-width" />
+    <meta name="format-detection" content="telephone=no, email=no, date=no, address=no">
+    <title>GFMES</title>
+    <style type="text/css">
+        p {
+            text-align:center;
+        }
+    </style>
+</head>
+
+<body>
+    <h2 style="text-align: center;">GFMES 安装包下载</h2>
+    <p><a id="downloadLink" href="SCMESAPP_V3_N1.0.2_D2022-05-26_crp.apk">如果文件未自动下载,可点击此处进行下载</a></p>
+</body>
+<script type="text/javascript">
+    autoDownloadApk();
+    function autoDownloadApk() 
+    {
+        var ele =  document.getElementById("downloadLink");
+        ele.click();
+
+    }
+
+</script>
+
+</html>