Przeglądaj źródła

1.增加Service管理类NetService,这样去掉了KcpPtrChannels静态字段,放到了KService中
2.RandomHelper改成了RandomGenerator,去掉了静态字段
3.去掉了CodeLoad.Codes枚举
4.一些try catch改回using

tanghai 3 lat temu
rodzic
commit
7b5e73c378
33 zmienionych plików z 234 dodań i 259 usunięć
  1. 2 0
      DotNet/App/Init.cs
  2. 1 1
      DotNet/Core/DotNet.Core.csproj
  3. 1 0
      DotNet/Tool/Init.cs
  4. 12 20
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/LoginHelper.cs
  5. 2 2
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Router/RouterAddressComponentSystem.cs
  6. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Router/RouterHelper.cs
  7. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Gate/R2G_GetLoginKeyHandler.cs
  8. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Realm/RealmGateAddressHelper.cs
  9. 5 5
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/DB/DBComponentSystem.cs
  10. 1 6
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/MessageInner/NetInnerComponentSystem.cs
  11. 1 1
      Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Router/RouterComponentSystem.cs
  12. 2 7
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetKcpComponentSystem.cs
  13. 3 49
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetThreadComponentSystem.cs
  14. 6 6
      Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Recast/PathfindingComponentSystem.cs
  15. 1 2
      Unity/Assets/Scripts/Codes/Model/Server/Module/Actor/ActorMessageSenderComponent.cs
  16. 1 1
      Unity/Assets/Scripts/Codes/Model/Server/Module/ActorLocation/LocationProxyComponent.cs
  17. 0 2
      Unity/Assets/Scripts/Codes/Model/Share/Module/Message/NetThreadComponent.cs
  18. 23 44
      Unity/Assets/Scripts/Codes/ModelView/Client/Module/Resource/ResourcesComponent.cs
  19. 17 32
      Unity/Assets/Scripts/Codes/ModelView/Client/Module/Resource/ResourcesLoaderComponent.cs
  20. 13 9
      Unity/Assets/Scripts/Core/Network/AService.cs
  21. 4 7
      Unity/Assets/Scripts/Core/Network/KChannel.cs
  22. 19 8
      Unity/Assets/Scripts/Core/Network/KService.cs
  23. 63 0
      Unity/Assets/Scripts/Core/Network/NetServices.cs
  24. 11 0
      Unity/Assets/Scripts/Core/Network/NetServices.cs.meta
  25. 2 0
      Unity/Assets/Scripts/Core/Network/TService.cs
  26. 2 0
      Unity/Assets/Scripts/Core/Network/WService.cs
  27. 14 16
      Unity/Assets/Scripts/Core/Object/RandomGenerator.cs
  28. 0 0
      Unity/Assets/Scripts/Core/Object/RandomGenerator.cs.meta
  29. 1 1
      Unity/Assets/Scripts/Editor/BuildEditor/BuildAssemblieEditor.cs
  30. 22 35
      Unity/Assets/Scripts/Mono/CodeLoader.cs
  31. 0 1
      Unity/Assets/Scripts/Mono/MonoBehaviour/GlobalConfig.cs
  32. 2 0
      Unity/Assets/Scripts/Mono/MonoBehaviour/Init.cs
  33. 0 1
      Unity/Directory.Build.props

+ 2 - 0
DotNet/App/Init.cs

@@ -27,11 +27,13 @@ namespace ET
 						.WithParsed(o => { options = o; });
 				
 				Game.AddSingleton(options);
+				Game.AddSingleton<RandomGenerator>();
 				Game.AddSingleton<TimeInfo>();
 				Game.AddSingleton<Logger>().ILog = new NLogger(Options.Instance.AppType.ToString(), Options.Instance.Process, "../Config/NLog/NLog.config");
 				Game.AddSingleton<ObjectPool>();
 				Game.AddSingleton<IdGenerater>();
 				Game.AddSingleton<EventSystem>();
+				Game.AddSingleton<NetServices>();
 				Game.AddSingleton<Root>();
 				
 				ETTask.ExceptionHandler += Log.Error;

+ 1 - 1
DotNet/Core/DotNet.Core.csproj

@@ -27,7 +27,7 @@
       <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
     </PropertyGroup>
     
-    <ItemGroup>
+    <ItemGroup> 
         <Compile Include="..\..\Unity\Assets\Scripts\Core\**\*.cs">
             <Link>Core\%(RecursiveDir)%(FileName)%(Extension)</Link>
         </Compile>

+ 1 - 0
DotNet/Tool/Init.cs

@@ -29,6 +29,7 @@ namespace ET.Server
                         .WithParsed(o => { options = o; });
 				
                 Game.AddSingleton(options);
+                Game.AddSingleton<RandomGenerator>();
                 Game.AddSingleton<TimeInfo>();
                 Game.AddSingleton<Logger>().ILog = new NLogger(Options.Instance.AppType.ToString(), Options.Instance.Process, "../Config/NLog/NLog.config");
                 Game.AddSingleton<ObjectPool>();

+ 12 - 20
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Login/LoginHelper.cs

@@ -11,30 +11,22 @@ namespace ET.Client
             try
             {
                 // 创建一个ETModel层的Session
-                R2C_Login r2CLogin;
-                Session session = null;
-                try
+                clientScene.RemoveComponent<RouterAddressComponent>();
+                // 获取路由跟realmDispatcher地址
+                RouterAddressComponent routerAddressComponent = clientScene.GetComponent<RouterAddressComponent>();
+                if (routerAddressComponent == null)
                 {
-                    clientScene.RemoveComponent<RouterAddressComponent>();
-                    // 获取路由跟realmDispatcher地址
-                    RouterAddressComponent routerAddressComponent = clientScene.GetComponent<RouterAddressComponent>();
-                    if (routerAddressComponent == null)
-                    {
-                        routerAddressComponent = clientScene.AddComponent<RouterAddressComponent, string, int>(ConstValue.RouterHttpHost, ConstValue.RouterHttpPort);
-                        await routerAddressComponent.Init();
-                        
-                        clientScene.AddComponent<NetKcpComponent, AddressFamily, int>(routerAddressComponent.RouterManagerIPAddress.AddressFamily, SessionStreamCallbackId.SessionStreamDispatcherClientOuter);
-                    }
-                    IPEndPoint realmAddress = routerAddressComponent.GetRealmAddress(account);
+                    routerAddressComponent = clientScene.AddComponent<RouterAddressComponent, string, int>(ConstValue.RouterHttpHost, ConstValue.RouterHttpPort);
+                    await routerAddressComponent.Init();
                     
-                    session = await RouterHelper.CreateRouterSession(clientScene, realmAddress);
-                    {
-                        r2CLogin = (R2C_Login) await session.Call(new C2R_Login() { Account = account, Password = password });
-                    }
+                    clientScene.AddComponent<NetKcpComponent, AddressFamily, int>(routerAddressComponent.RouterManagerIPAddress.AddressFamily, SessionStreamCallbackId.SessionStreamDispatcherClientOuter);
                 }
-                finally
+                IPEndPoint realmAddress = routerAddressComponent.GetRealmAddress(account);
+                
+                R2C_Login r2CLogin;
+                using (Session session = await RouterHelper.CreateRouterSession(clientScene, realmAddress))
                 {
-                    session?.Dispose();
+                    r2CLogin = (R2C_Login) await session.Call(new C2R_Login() { Account = account, Password = password });
                 }
 
                 // 创建一个gate Session,并且保存到SessionComponent中

+ 2 - 2
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Router/RouterAddressComponentSystem.cs

@@ -26,7 +26,7 @@ namespace ET.Client
 
         private static async ETTask GetAllRouter(this RouterAddressComponent self)
         {
-            string url = $"http://{self.RouterManagerHost}:{self.RouterManagerPort}/get_router?v={RandomHelper.RandUInt32()}";
+            string url = $"http://{self.RouterManagerHost}:{self.RouterManagerPort}/get_router?v={RandomGenerator.Instance.RandUInt32()}";
             Log.Debug($"start get router info: {url}");
             string routerInfo = await HttpClientHelper.Get(url);
             Log.Debug($"recv router info: {routerInfo}");
@@ -35,7 +35,7 @@ namespace ET.Client
             Log.Debug($"start get router info finish: {JsonHelper.ToJson(httpGetRouterResponse)}");
             
             // 打乱顺序
-            RandomHelper.BreakRank(self.Info.Routers);
+            RandomGenerator.Instance.BreakRank(self.Info.Routers);
             
             self.WaitTenMinGetAllRouter().Coroutine();
         }

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Client/Demo/Router/RouterHelper.cs

@@ -41,7 +41,7 @@ namespace ET.Client
         // 向router申请
         private static async ETTask<uint> Connect(IPEndPoint routerAddress, IPEndPoint realAddress, uint localConn, uint remoteConn)
         {
-            uint connectId = RandomHelper.RandUInt32();
+            uint connectId = RandomGenerator.Instance.RandUInt32();
             
             using Socket socket = new Socket(routerAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
             

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Gate/R2G_GetLoginKeyHandler.cs

@@ -8,7 +8,7 @@ namespace ET.Server
 	{
 		protected override async ETTask Run(Scene scene, R2G_GetLoginKey request, G2R_GetLoginKey response, Action reply)
 		{
-			long key = RandomHelper.RandInt64();
+			long key = RandomGenerator.Instance.RandInt64();
 			scene.GetComponent<GateSessionKeyComponent>().Add(key, request.Account);
 			response.Key = key;
 			response.GateId = scene.Id;

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Demo/Realm/RealmGateAddressHelper.cs

@@ -9,7 +9,7 @@ namespace ET.Server
 		{
 			List<StartSceneConfig> zoneGates = StartSceneConfigCategory.Instance.Gates[zone];
 			
-			int n = RandomHelper.RandomNumber(0, zoneGates.Count);
+			int n = RandomGenerator.Instance.RandomNumber(0, zoneGates.Count);
 
 			return zoneGates[n];
 		}

+ 5 - 5
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/DB/DBComponentSystem.cs

@@ -43,7 +43,7 @@ namespace ET.Server
 	    public static async ETTask<List<T>> Query<T>(this DBComponent self, Expression<Func<T, bool>> filter, string collection = null)
 			    where T : Entity
 	    {
-		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomGenerator.Instance.RandInt64() % DBComponent.TaskCount))
 		    {
 			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filter);
 
@@ -89,7 +89,7 @@ namespace ET.Server
 
 	    public static async ETTask<List<T>> QueryJson<T>(this DBComponent self, string json, string collection = null) where T : Entity
 	    {
-		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomGenerator.Instance.RandInt64() % DBComponent.TaskCount))
 		    {
 			    FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
 			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filterDefinition);
@@ -99,7 +99,7 @@ namespace ET.Server
 
 	    public static async ETTask<List<T>> QueryJson<T>(this DBComponent self, long taskId, string json, string collection = null) where T : Entity
 	    {
-		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomGenerator.Instance.RandInt64() % DBComponent.TaskCount))
 		    {
 			    FilterDefinition<T> filterDefinition = new JsonFilterDefinition<T>(json);
 			    IAsyncCursor<T> cursor = await self.GetCollection<T>(collection).FindAsync(filterDefinition);
@@ -118,7 +118,7 @@ namespace ET.Server
 			    collection = typeof (T).Name;
 		    }
 		    
-		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomGenerator.Instance.RandInt64() % DBComponent.TaskCount))
 		    {
 			    await self.GetCollection(collection).InsertManyAsync(list);
 		    }
@@ -229,7 +229,7 @@ namespace ET.Server
 
 	    public static async ETTask<long> Remove<T>(this DBComponent self, Expression<Func<T, bool>> filter, string collection = null) where T : Entity
 	    {
-		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomHelper.RandInt64() % DBComponent.TaskCount))
+		    using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.DB, RandomGenerator.Instance.RandInt64() % DBComponent.TaskCount))
 		    {
 			    DeleteResult result = await self.GetCollection<T>(collection).DeleteManyAsync(filter);
 

+ 1 - 6
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/MessageInner/NetInnerComponentSystem.cs

@@ -19,8 +19,6 @@ namespace ET.Server
                 self.Service = new KService(NetThreadComponent.Instance.ThreadSynchronizationContext, AddressFamily.InterNetwork, ServiceType.Inner);
                 self.Service.ErrorCallback += self.OnError;
                 self.Service.ReadCallback += self.OnRead;
-
-                NetThreadComponent.Instance.Add(self.Service);
             }
         }
 
@@ -36,8 +34,6 @@ namespace ET.Server
                 self.Service.ErrorCallback += self.OnError;
                 self.Service.ReadCallback += self.OnRead;
                 self.Service.AcceptCallback += self.OnAccept;
-
-                NetThreadComponent.Instance.Add(self.Service);
             }
         }
 
@@ -46,8 +42,7 @@ namespace ET.Server
         {
             protected override void Destroy(NetInnerComponent self)
             {
-                NetThreadComponent.Instance.Remove(self.Service);
-                self.Service.Destroy();
+                self.Service.Dispose();
             }
         }
 

+ 1 - 1
Unity/Assets/Scripts/Codes/Hotfix/Server/Module/Router/RouterComponentSystem.cs

@@ -262,7 +262,7 @@ namespace ET.Server
                     self.ConnectIdNodes.TryGetValue(connectId, out routerNode);
                     if (routerNode == null)
                     {
-                        outerConn = RandomHelper.RandUInt32();
+                        outerConn = RandomGenerator.Instance.RandUInt32();
                         routerNode = self.New(realAddress, connectId, outerConn, innerConn, self.CloneAddress());
                         Log.Info($"router create: {realAddress} {connectId} {outerConn} {innerConn} {routerNode.SyncIpEndPoint}");
                         self.OuterNodes.Add(routerNode.OuterConn, routerNode);

+ 2 - 7
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetKcpComponentSystem.cs

@@ -17,8 +17,6 @@ namespace ET
                 self.Service = new KService(NetThreadComponent.Instance.ThreadSynchronizationContext, addressFamily, ServiceType.Outer);
                 self.Service.ErrorCallback += (channelId, error) => self.OnError(channelId, error);
                 self.Service.ReadCallback += (channelId, Memory) => self.OnRead(channelId, Memory);
-
-                NetThreadComponent.Instance.Add(self.Service);
             }
         }
 
@@ -33,8 +31,6 @@ namespace ET
                 self.Service.ErrorCallback += (channelId, error) => self.OnError(channelId, error);
                 self.Service.ReadCallback += (channelId, Memory) => self.OnRead(channelId, Memory);
                 self.Service.AcceptCallback += (channelId, IPAddress) => self.OnAccept(channelId, IPAddress);
-
-                NetThreadComponent.Instance.Add(self.Service);
             }
         }
 
@@ -43,8 +39,7 @@ namespace ET
         {
             protected override void Destroy(NetKcpComponent self)
             {
-                NetThreadComponent.Instance.Remove(self.Service);
-                self.Service.Destroy();
+                self.Service.Dispose();
             }
         }
         
@@ -93,7 +88,7 @@ namespace ET
 
         public static Session Create(this NetKcpComponent self, IPEndPoint realIPEndPoint)
         {
-            long channelId = RandomHelper.RandInt64();
+            long channelId = RandomGenerator.Instance.RandInt64();
             Session session = self.AddChildWithId<Session, AService>(channelId, self.Service);
             session.RemoteAddress = realIPEndPoint;
             session.AddComponent<SessionIdleCheckerComponent, int>(NetThreadComponent.checkInteral);

+ 3 - 49
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Message/NetThreadComponentSystem.cs

@@ -1,7 +1,4 @@
-using System;
-using System.Threading;
-
-namespace ET
+namespace ET
 {
     [FriendOf(typeof(NetThreadComponent))]
     public static class NetThreadComponentSystem
@@ -12,7 +9,7 @@ namespace ET
             protected override void Awake(NetThreadComponent self)
             {
                 NetThreadComponent.Instance = self;
-            
+                
                 self.ThreadSynchronizationContext = ThreadSynchronizationContext.Instance;
             }
         }
@@ -22,51 +19,8 @@ namespace ET
         {
             protected override void LateUpdate(NetThreadComponent self)
             {
-                foreach (AService service in self.Services)
-                {
-                    service.Update();
-                }
-            }
-        }
-    
-        [ObjectSystem]
-        public class NetThreadComponentDestroySystem: DestroySystem<NetThreadComponent>
-        {
-            protected override void Destroy(NetThreadComponent self)
-            {
-                self.Stop();
+                NetServices.Instance.Update();
             }
         }
-
-        public static void Stop(this NetThreadComponent self)
-        {
-        }
-
-        public static void Add(this NetThreadComponent self, AService kService)
-        {
-            // 这里要去下一帧添加,避免foreach错误
-            self.ThreadSynchronizationContext.PostNext(() =>
-            {
-                if (kService.IsDispose())
-                {
-                    return;
-                }
-                self.Services.Add(kService);
-            });
-        }
-        
-        public static void Remove(this NetThreadComponent self, AService kService)
-        {
-            // 这里要去下一帧删除,避免foreach错误
-            self.ThreadSynchronizationContext.PostNext(() =>
-            {
-                if (kService.IsDispose())
-                {
-                    return;
-                }
-                self.Services.Remove(kService);
-            });
-        }
-        
     }
 }

+ 6 - 6
Unity/Assets/Scripts/Codes/Hotfix/Share/Module/Recast/PathfindingComponentSystem.cs

@@ -79,8 +79,8 @@ namespace ET
                 throw new Exception($"pathfinding raduis is too large,cur: {raduis}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
             }
             
-            int degrees = RandomHelper.RandomNumber(0, 360);
-            float r = RandomHelper.RandomNumber(0, (int) (raduis * 1000)) / 1000f;
+            int degrees = RandomGenerator.Instance.RandomNumber(0, 360);
+            float r = RandomGenerator.Instance.RandomNumber(0, (int) (raduis * 1000)) / 1000f;
 
             float x = r * Mathf.Cos(MathHelper.DegToRad(degrees));
             float z = r * Mathf.Sin(MathHelper.DegToRad(degrees));
@@ -111,8 +111,8 @@ namespace ET
                 throw new Exception($"pathfinding rectangle is too large,width: {width} height: {height}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
             }
             
-            float x = RandomHelper.RandomNumber(-width, width);
-            float z = RandomHelper.RandomNumber(-height, height);
+            float x = RandomGenerator.Instance.RandomNumber(-width, width);
+            float z = RandomGenerator.Instance.RandomNumber(-height, height);
 
             Vector3 findpos = new Vector3(pos.x + x, pos.y, pos.z + z);
 
@@ -131,8 +131,8 @@ namespace ET
                 throw new Exception($"pathfinding raduis is too large,cur: {maxRadius}, max: {PathfindingComponent.FindRandomNavPosMaxRadius}");
             }
             
-            int degrees = RandomHelper.RandomNumber(0, 360);
-            float r = RandomHelper.RandomNumber((int) (minRadius * 1000), (int) (maxRadius * 1000)) / 1000f;
+            int degrees = RandomGenerator.Instance.RandomNumber(0, 360);
+            float r = RandomGenerator.Instance.RandomNumber((int) (minRadius * 1000), (int) (maxRadius * 1000)) / 1000f;
 
             float x = r * Mathf.Cos(MathHelper.DegToRad(degrees));
             float z = r * Mathf.Sin(MathHelper.DegToRad(degrees));

+ 1 - 2
Unity/Assets/Scripts/Codes/Model/Server/Module/Actor/ActorMessageSenderComponent.cs

@@ -5,8 +5,7 @@ namespace ET.Server
     [ComponentOf(typeof(Scene))]
     public class ActorMessageSenderComponent: Entity, IAwake, IDestroy
     {
-        [StaticField]
-        public static long TIMEOUT_TIME = 40 * 1000;
+        public const long TIMEOUT_TIME = 40 * 1000;
 
         public static ActorMessageSenderComponent Instance { get; set; }
 

+ 1 - 1
Unity/Assets/Scripts/Codes/Model/Server/Module/ActorLocation/LocationProxyComponent.cs

@@ -3,7 +3,7 @@
     [ComponentOf(typeof(Scene))]
     public class LocationProxyComponent: Entity, IAwake, IDestroy
     {
-        [StaticField()]
+        [StaticField]
         public static LocationProxyComponent Instance;
     }
 }

+ 0 - 2
Unity/Assets/Scripts/Codes/Model/Share/Module/Message/NetThreadComponent.cs

@@ -13,7 +13,5 @@ namespace ET
         public const int sendMaxIdleTime = 60000;
 
         public ThreadSynchronizationContext ThreadSynchronizationContext { get; set; }
-        
-        public HashSet<AService> Services = new HashSet<AService>();
     }
 }

+ 23 - 44
Unity/Assets/Scripts/Codes/ModelView/Client/Module/Resource/ResourcesComponent.cs

@@ -248,17 +248,11 @@ namespace ET.Client
             //Log.Debug($"-----------dep unload start {assetBundleName} dep: {dependencies.ToList().ListToString()}");
             foreach (string dependency in dependencies)
             {
-                CoroutineLock coroutineLock = null;
-                try
+                using (await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, assetBundleName.GetHashCode()))
                 {
-                    coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, assetBundleName.GetHashCode());
                     self.UnloadOneBundle(dependency, unload);
                     await TimerComponent.Instance.WaitFrameAsync();
                 }
-                finally
-                {
-                    coroutineLock?.Dispose();
-                }
             }
             //Log.Debug($"-----------dep unload finish {assetBundleName} dep: {dependencies.ToList().ListToString()}");
         }
@@ -429,22 +423,15 @@ namespace ET.Client
             {
                 async ETTask LoadDependency(string dependency, List<ABInfo> abInfosList)
                 {
-                    CoroutineLock coroutineLock = null;
-                    try
+                    using CoroutineLock coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode());
+                    
+                    ABInfo abInfo = await self.LoadOneBundleAsync(dependency);
+                    if (abInfo == null || abInfo.RefCount > 1)
                     {
-                        coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, dependency.GetHashCode());
-                        ABInfo abInfo = await self.LoadOneBundleAsync(dependency);
-                        if (abInfo == null || abInfo.RefCount > 1)
-                        {
-                            return;
-                        }
-
-                        abInfosList.Add(abInfo);
-                    }
-                    finally
-                    {
-                        coroutineLock?.Dispose();
+                        return;
                     }
+
+                    abInfosList.Add(abInfo);
                 }
 
                 // LoadFromFileAsync部分可以并发加载
@@ -539,35 +526,27 @@ namespace ET.Client
         // 加载ab包中的all assets
         private static async ETTask LoadOneBundleAllAssets(this ResourcesComponent self, ABInfo abInfo)
         {
-            CoroutineLock coroutineLock = null;
-            try
+            using CoroutineLock coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode());
+            
+            if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
             {
-                coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.Resources, abInfo.Name.GetHashCode());
+                return;
+            }
 
-                if (abInfo.IsDisposed || abInfo.AlreadyLoadAssets)
-                {
-                    return;
-                }
+            if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
+            {
+                // 异步load资源到内存cache住
+                AssetBundleRequest request = abInfo.AssetBundle.LoadAllAssetsAsync();
+                await request;
+                UnityEngine.Object[] assets = request.allAssets;
 
-                if (abInfo.AssetBundle != null && !abInfo.AssetBundle.isStreamedSceneAssetBundle)
+                foreach (UnityEngine.Object asset in assets)
                 {
-                    // 异步load资源到内存cache住
-                    AssetBundleRequest request = abInfo.AssetBundle.LoadAllAssetsAsync();
-                    await request;
-                    UnityEngine.Object[] assets = request.allAssets;
-
-                    foreach (UnityEngine.Object asset in assets)
-                    {
-                        self.AddResource(abInfo.Name, asset.name, asset);
-                    }
+                    self.AddResource(abInfo.Name, asset.name, asset);
                 }
-
-                abInfo.AlreadyLoadAssets = true;
-            }
-            finally
-            {
-                coroutineLock?.Dispose();
             }
+
+            abInfo.AlreadyLoadAssets = true;
         }
 
         public static string DebugString(this ResourcesComponent self)

+ 17 - 32
Unity/Assets/Scripts/Codes/ModelView/Client/Module/Resource/ResourcesLoaderComponent.cs

@@ -27,23 +27,15 @@ namespace ET.Client
         
                             foreach (string abName in list)
                             {
-                                CoroutineLock coroutineLock = null;
-                                try
+                                using CoroutineLock coroutineLock =
+                                        await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ResourcesLoader, abName.GetHashCode(), 0);
                                 {
-                                    coroutineLock =
-                                            await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ResourcesLoader, abName.GetHashCode(), 0);
+                                    if (ResourcesComponent.Instance == null)
                                     {
-                                        if (ResourcesComponent.Instance == null)
-                                        {
-                                            return;
-                                        }
-        
-                                        await ResourcesComponent.Instance.UnloadBundleAsync(abName);
+                                        return;
                                     }
-                                }
-                                finally
-                                {
-                                    coroutineLock?.Dispose();
+        
+                                    await ResourcesComponent.Instance.UnloadBundleAsync(abName);
                                 }
                             }
                         }
@@ -55,28 +47,21 @@ namespace ET.Client
         
         public static async ETTask LoadAsync(this ResourcesLoaderComponent self, string ab)
         {
-            CoroutineLock coroutineLock = null;
-            try
+            using CoroutineLock coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ResourcesLoader, ab.GetHashCode(), 0);
+                    
+            if (self.IsDisposed)
             {
-                coroutineLock = await CoroutineLockComponent.Instance.Wait(CoroutineLockType.ResourcesLoader, ab.GetHashCode(), 0);
-                if (self.IsDisposed)
-                {
-                    Log.Error($"resourceload already disposed {ab}");
-                    return;
-                }
-
-                if (self.LoadedResource.Contains(ab))
-                {
-                    return;
-                }
-
-                self.LoadedResource.Add(ab);
-                await ResourcesComponent.Instance.LoadBundleAsync(ab);
+                Log.Error($"resourceload already disposed {ab}");
+                return;
             }
-            finally
+
+            if (self.LoadedResource.Contains(ab))
             {
-                coroutineLock?.Dispose();
+                return;
             }
+
+            self.LoadedResource.Add(ab);
+            await ResourcesComponent.Instance.LoadBundleAsync(ab);
         }
     }
     

+ 13 - 9
Unity/Assets/Scripts/Core/Network/AService.cs

@@ -6,10 +6,22 @@ namespace ET
 {
     public abstract class AService: IDisposable
     {
+        public int Id { get; set; }
+        
         public ServiceType ServiceType { get; protected set; }
         
         public ThreadSynchronizationContext ThreadSynchronizationContext;
         
+        protected AService()
+        {
+            NetServices.Instance.Add(this);
+        }
+
+        public virtual void Dispose()
+        {
+            NetServices.Instance.Remove(this);
+        }
+        
         // localConn放在低32bit
         private long connectIdGenerater = int.MaxValue;
         public long CreateConnectChannelId(uint localConn)
@@ -19,7 +31,7 @@ namespace ET
         
         public uint CreateRandomLocalConn()
         {
-            return (1u << 30) | RandomHelper.RandUInt32();
+            return (1u << 30) | RandomGenerator.Instance.RandUInt32();
         }
 
         // localConn放在低32bit
@@ -30,7 +42,6 @@ namespace ET
         }
 
 
-
         public abstract void Update();
 
         public abstract void Remove(long id);
@@ -39,8 +50,6 @@ namespace ET
 
         protected abstract void Get(long id, IPEndPoint address);
 
-        public abstract void Dispose();
-
         protected abstract void Send(long channelId, long actorId, MemoryStream stream);
         
         protected void OnAccept(long channelId, IPEndPoint ipEndPoint)
@@ -65,11 +74,6 @@ namespace ET
         public Action<long, int> ErrorCallback;
         public Action<long, MemoryStream> ReadCallback;
 
-        public void Destroy()
-        {
-            this.Dispose();
-        }
-
         public void RemoveChannel(long channelId)
         {
             this.Remove(channelId);

+ 4 - 7
Unity/Assets/Scripts/Core/Network/KChannel.cs

@@ -15,9 +15,6 @@ namespace ET
 	
 	public class KChannel : AChannel
 	{
-		[StaticField]
-		public static readonly Dictionary<IntPtr, KChannel> KcpPtrChannels = new Dictionary<IntPtr, KChannel>();
-		
 		public KService Service;
 		
 		private Socket socket;
@@ -48,7 +45,8 @@ namespace ET
 		
 		private void InitKcp()
 		{
-			KcpPtrChannels.Add(this.kcp, this);
+			this.Service.KcpPtrChannels.Add(this.kcp, this);
+			
 			switch (this.Service.ServiceType)
 			{
 				case ServiceType.Inner:
@@ -101,7 +99,7 @@ namespace ET
 			this.RemoteConn = remoteConn;
 			this.RemoteAddress = remoteEndPoint;
 			this.socket = socket;
-			this.kcp = Kcp.KcpCreate(this.RemoteConn, IntPtr.Zero);
+			this.kcp = Kcp.KcpCreate(this.RemoteConn, new IntPtr(this.Service.Id));
 			this.InitKcp();
 			
 			this.lastRecvTime = kService.TimeNow;
@@ -136,7 +134,6 @@ namespace ET
 
 			if (this.kcp != IntPtr.Zero)
 			{
-				KcpPtrChannels.Remove(this.kcp);
 				Kcp.KcpRelease(this.kcp);
 				this.kcp = IntPtr.Zero;
 			}
@@ -152,7 +149,7 @@ namespace ET
 				return;
 			}
 
-			this.kcp = Kcp.KcpCreate(this.RemoteConn, IntPtr.Zero);
+			this.kcp = Kcp.KcpCreate(this.RemoteConn, new IntPtr(this.Service.Id));
 			this.InitKcp();
 
 			Log.Info($"channel connected: {this.Id} {this.LocalConn} {this.RemoteConn} {this.RemoteAddress}");

+ 19 - 8
Unity/Assets/Scripts/Core/Network/KService.cs

@@ -1,5 +1,4 @@
 using System;
-using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
@@ -29,6 +28,8 @@ namespace ET
 
     public sealed class KService: AService
     {
+        public readonly Dictionary<IntPtr, KChannel> KcpPtrChannels = new Dictionary<IntPtr, KChannel>();
+        
         // KService创建的时间
         private readonly long startTime;
 
@@ -52,9 +53,6 @@ namespace ET
             Kcp.KcpSetoutput(KcpOutput);
         }
         
-        [StaticField]
-        private static readonly byte[] logBuffer = new byte[1024];
-
 #if ENABLE_IL2CPP
 		[AOT.MonoPInvokeCallback(typeof(KcpOutput))]
 #endif
@@ -62,8 +60,12 @@ namespace ET
         {
             try
             {
-                Marshal.Copy(bytes, logBuffer, 0, len);
-                Log.Info(logBuffer.ToStr(0, len));
+                unsafe
+                {
+                    //Marshal.Copy(bytes, logBuffer, 0, len);
+                    Span<byte> span = new Span<byte>(bytes.ToPointer(), len);
+                    Log.Info(span.ToString());
+                }
             }
             catch (Exception e)
             {
@@ -82,8 +84,10 @@ namespace ET
                 {
                     return 0;
                 }
-
-                if (!KChannel.KcpPtrChannels.TryGetValue(kcp, out KChannel kChannel))
+                
+                KService kService = NetServices.Instance.Get(user.ToInt32()) as KService;
+                
+                if (!kService.KcpPtrChannels.TryGetValue(kcp, out KChannel kChannel))
                 {
                     return 0;
                 }
@@ -137,6 +141,8 @@ namespace ET
                 uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                 this.socket.IOControl((int) SIO_UDP_CONNRESET, new[] { Convert.ToByte(false) }, null);
             }
+            
+            NetServices.Instance.Add(this);
         }
 
         public void ChangeAddress(long id, IPEndPoint address)
@@ -180,6 +186,8 @@ namespace ET
 
         public override void Dispose()
         {
+            base.Dispose();
+            
             foreach (long channelId in this.idChannels.Keys.ToArray())
             {
                 this.Remove(channelId);
@@ -484,6 +492,9 @@ namespace ET
                     this.waitConnectChannels.Remove(kChannel.RemoteConn);
                 }
             }
+
+            this.KcpPtrChannels.Remove(kChannel.kcp);
+            
             kChannel.Dispose();
         }
 

+ 63 - 0
Unity/Assets/Scripts/Core/Network/NetServices.cs

@@ -0,0 +1,63 @@
+using System;
+using System.Collections.Generic;
+
+namespace ET
+{
+    public class NetServices: Singleton<NetServices>
+    {
+        // 一个进程最多1024个Service
+        private readonly AService[] Services = new AService[1024];
+
+        private int index;
+        
+        private readonly Queue<int> queue = new Queue<int>();
+
+        public AService Get(int id)
+        {
+            return this.Services[id];
+        }
+
+        public void Add(AService aService)
+        {
+            for (int j = 0; j < 1024; ++j)
+            {
+                if (++this.index == 1024)
+                {
+                    this.index = 0;
+                }
+
+                if (this.Services[this.index] != null)
+                {
+                    continue;
+                }
+
+                aService.Id = this.index;
+                this.Services[aService.Id] = aService;
+                this.queue.Enqueue(aService.Id);
+                return;
+            }
+            throw new Exception("not found service id");
+        }
+
+        public void Remove(AService aService)
+        {
+            this.Services[aService.Id] = null;
+        }
+
+        public void Update()
+        {
+            int count = this.queue.Count;
+            while (count-- > 0)
+            {
+                int serviceId = this.queue.Dequeue();
+                AService service = this.Services[serviceId];
+                if (service == null)
+                {
+                    continue;
+                }
+                this.queue.Enqueue(serviceId);
+                service.Update();
+            }
+        }
+    }
+}

+ 11 - 0
Unity/Assets/Scripts/Core/Network/NetServices.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 8d287718ca1c8b1449db4794f0a3524b
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 2 - 0
Unity/Assets/Scripts/Core/Network/TService.cs

@@ -122,6 +122,8 @@ namespace ET
 		
 		public override void Dispose()
 		{
+			base.Dispose();
+			
 			this.acceptor?.Close();
 			this.acceptor = null;
 			this.innArgs.Dispose();

+ 2 - 0
Unity/Assets/Scripts/Core/Network/WService.cs

@@ -71,6 +71,8 @@ namespace ET
 
         public override void Dispose()
         {
+            base.Dispose();
+            
             this.ThreadSynchronizationContext = null;
             this.httpListener?.Close();
             this.httpListener = null;

+ 14 - 16
Unity/Assets/Scripts/Core/Helper/RandomHelper.cs → Unity/Assets/Scripts/Core/Object/RandomGenerator.cs

@@ -4,31 +4,29 @@ using Random = System.Random;
 
 namespace ET
 {
-    public static class RandomHelper
+    public class RandomGenerator: Singleton<RandomGenerator>
     {
-        [StaticField]
-        private static readonly Random random = new Random(Guid.NewGuid().GetHashCode());
+        private readonly Random random = new Random(Guid.NewGuid().GetHashCode());
 
-        [StaticField]
-        private static readonly byte[] byte8 = new byte[8];
+        private readonly byte[] byte8 = new byte[8];
 
-        public static ulong RandUInt64()
+        public ulong RandUInt64()
         {
             random.NextBytes(byte8);
             return BitConverter.ToUInt64(byte8, 0);
         }
 
-        public static int RandInt32()
+        public int RandInt32()
         {
             return random.Next();
         }
 
-        public static uint RandUInt32()
+        public uint RandUInt32()
         {
             return (uint) random.Next();
         }
 
-        public static long RandInt64()
+        public long RandInt64()
         {
             random.NextBytes(byte8);
             return BitConverter.ToInt64(byte8, 0);
@@ -40,13 +38,13 @@ namespace ET
         /// <param name="lower"></param>
         /// <param name="upper"></param>
         /// <returns></returns>
-        public static int RandomNumber(int lower, int upper)
+        public int RandomNumber(int lower, int upper)
         {
             int value = random.Next(lower, upper);
             return value;
         }
 
-        public static long NextLong(long minValue, long maxValue)
+        public long NextLong(long minValue, long maxValue)
         {
             if (minValue > maxValue)
             {
@@ -57,17 +55,17 @@ namespace ET
             return minValue + (long) (random.NextDouble() * num);
         }
 
-        public static bool RandomBool()
+        public bool RandomBool()
         {
             return random.Next(2) == 0;
         }
 
-        public static T RandomArray<T>(this T[] array)
+        public T RandomArray<T>(T[] array)
         {
             return array[RandomNumber(0, array.Length)];
         }
 
-        public static T RandomArray<T>(this List<T> array)
+        public T RandomArray<T>(List<T> array)
         {
             return array[RandomNumber(0, array.Count)];
         }
@@ -77,7 +75,7 @@ namespace ET
         /// </summary>
         /// <typeparam name="T"></typeparam>
         /// <param name="arr">要打乱的数组</param>
-        public static void BreakRank<T>(this List<T> arr)
+        public void BreakRank<T>(List<T> arr)
         {
             if (arr == null || arr.Count < 2)
             {
@@ -91,7 +89,7 @@ namespace ET
             }
         }
 
-        public static float RandFloat01()
+        public float RandFloat01()
         {
             int a = RandomNumber(0, 1000000);
             return a / 1000000f;

+ 0 - 0
Unity/Assets/Scripts/Core/Helper/RandomHelper.cs.meta → Unity/Assets/Scripts/Core/Object/RandomGenerator.cs.meta


+ 1 - 1
Unity/Assets/Scripts/Editor/BuildEditor/BuildAssemblieEditor.cs

@@ -145,7 +145,7 @@ namespace ET
                 File.Delete(file);
             }
             
-            int random = RandomHelper.RandomNumber(100000000, 999999999);
+            int random = RandomGenerator.Instance.RandomNumber(100000000, 999999999);
             string logicFile = $"Hotfix_{random}";
             
             List<string> codes;

+ 22 - 35
Unity/Assets/Scripts/Mono/CodeLoader.cs

@@ -14,18 +14,28 @@ namespace ET
 		{
 			if (Define.EnableCodes)
 			{
-				Init.Instance.GlobalConfig.LoadMode = LoadMode.Codes;
+				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
+				Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(assemblies);
+				EventSystem.Instance.Add(types);
+				foreach (Assembly ass in assemblies)
+				{
+					string name = ass.GetName().Name;
+					if (name == "Unity.Codes")
+					{
+						this.assembly = ass;
+					}
+				}
+				
+				IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
+				start.Run();
+				return;
 			}
-			
+
+
 			switch (Init.Instance.GlobalConfig.LoadMode)
 			{
 				case LoadMode.Mono:
 				{
-					if (Define.EnableCodes)
-					{
-						throw new Exception("LoadMode.Mono must remove ENABLE_CODE define, please use ET/ChangeDefine/Remove ENABLE_CODE to Remove define");
-					}
-					
 					Dictionary<string, UnityEngine.Object> dictionary = AssetsBundleHelper.LoadBundle("code.unity3d");
 					byte[] assBytes = ((TextAsset)dictionary["Code.dll"]).bytes;
 					byte[] pdbBytes = ((TextAsset)dictionary["Code.pdb"]).bytes;
@@ -36,46 +46,23 @@ namespace ET
 					Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (Game).Assembly, this.assembly);
 					EventSystem.Instance.Add(types);
 					
+					IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
+					start.Run();
 					break;
 				}
 				case LoadMode.Reload:
 				{
-					if (Define.EnableCodes)
-					{
-						throw new Exception("LoadMode.Reload must remove ENABLE_CODE define, please use ET/ChangeDefine/Remove ENABLE_CODE to Remove define");
-					}
-					
 					byte[] assBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Model.dll"));
 					byte[] pdbBytes = File.ReadAllBytes(Path.Combine(Define.BuildOutputDir, "Model.pdb"));
 					
 					assembly = Assembly.Load(assBytes, pdbBytes);
 					this.LoadHotfix();
-					break;
-				}
-				case LoadMode.Codes:
-				{
-					if (!Define.EnableCodes)
-					{
-						throw new Exception("LoadMode.Codes must add ENABLE_CODE define, please use ET/ChangeDefine/Add ENABLE_CODE to add define");
-					}
-
-					Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
-					Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(assemblies);
-					EventSystem.Instance.Add(types);
-					foreach (Assembly ass in assemblies)
-					{
-						string name = ass.GetName().Name;
-						if (name == "Unity.Codes")
-						{
-							this.assembly = ass;
-						}
-					}
+					
+					IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
+					start.Run();
 					break;
 				}
 			}
-			
-			IStaticMethod start = new StaticMethod(assembly, "ET.Entry", "Start");
-			start.Run();
 		}
 
 		// 热重载调用下面两个方法

+ 0 - 1
Unity/Assets/Scripts/Mono/MonoBehaviour/GlobalConfig.cs

@@ -7,7 +7,6 @@ namespace ET
     {
         Mono = 1,
         Reload = 2,
-        Codes = 3,
     }
 
     public enum CodeMode

+ 2 - 0
Unity/Assets/Scripts/Mono/MonoBehaviour/Init.cs

@@ -32,11 +32,13 @@ namespace ET
 				.WithParsed(o => { options = o; });
 			
 			Game.AddSingleton(options);
+			Game.AddSingleton<RandomGenerator>();
 			Game.AddSingleton<TimeInfo>();
 			Game.AddSingleton<Logger>().ILog = new UnityLogger();
 			Game.AddSingleton<ObjectPool>();
 			Game.AddSingleton<IdGenerater>();
 			Game.AddSingleton<EventSystem>();
+			Game.AddSingleton<NetServices>();
 			Game.AddSingleton<Root>();
 			
 			ETTask.ExceptionHandler += Log.Error;

+ 0 - 1
Unity/Directory.Build.props

@@ -2,6 +2,5 @@
   <PropertyGroup>
     <LangVersion>10.0</LangVersion>
     <NoWarn>0169,0649,3021</NoWarn>
-    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
   </PropertyGroup>
 </Project>