tanghai 9 лет назад
Родитель
Сommit
6e28634267
100 измененных файлов с 4569 добавлено и 4569 удалено
  1. 139 139
      CSharp/CSharp.sln
  2. 6 6
      CSharp/Exe/Profile/App.config
  3. 72 72
      CSharp/Exe/Profile/Profile.csproj
  4. 15 15
      CSharp/Exe/Profile/Program.cs
  5. 38 38
      CSharp/Exe/Profile/Properties/AssemblyInfo.cs
  6. 16 16
      CSharp/Game/Controller/BehaviorTreeNode/Not.cs
  7. 23 23
      CSharp/Game/Controller/BehaviorTreeNode/Selector.cs
  8. 23 23
      CSharp/Game/Controller/BehaviorTreeNode/Sequence.cs
  9. 8 8
      CSharp/Game/Controller/ConfigCategory/BuffCategory.cs
  10. 8 8
      CSharp/Game/Controller/ConfigCategory/GlobalCategory.cs
  11. 29 29
      CSharp/Game/Controller/ConfigCategory/ServerInfoCategory.cs
  12. 8 8
      CSharp/Game/Controller/ConfigCategory/UnitCategory.cs
  13. 81 81
      CSharp/Game/Controller/Controller.csproj
  14. 18 18
      CSharp/Game/Controller/Event/BuffTimeoutEvent.cs
  15. 14 14
      CSharp/Game/Controller/Factory/UnitPlayerFactory.cs
  16. 19 19
      CSharp/Game/Controller/Message/CMsgLoginEvent.cs
  17. 38 38
      CSharp/Game/Controller/Properties/AssemblyInfo.cs
  18. 55 55
      CSharp/Game/Model/ACategory.cs
  19. 18 18
      CSharp/Game/Model/AConfig.cs
  20. 26 26
      CSharp/Game/Model/AEventAttribute.cs
  21. 70 70
      CSharp/Game/Model/Actor.cs
  22. 16 16
      CSharp/Game/Model/BehaviorTree/BehaviorTree.cs
  23. 55 55
      CSharp/Game/Model/BehaviorTree/Node.cs
  24. 14 14
      CSharp/Game/Model/BehaviorTree/NodeAttribute.cs
  25. 129 129
      CSharp/Game/Model/Buff.cs
  26. 7 7
      CSharp/Game/Model/BuffType.cs
  27. 27 27
      CSharp/Game/Model/Component/ActorComponent.cs
  28. 91 91
      CSharp/Game/Model/Component/BehaviorTreeComponent.cs
  29. 129 129
      CSharp/Game/Model/Component/BuffComponent.cs
  30. 15 15
      CSharp/Game/Model/Component/ChannelUnitInfoComponent.cs
  31. 76 76
      CSharp/Game/Model/Component/ConfigComponent.cs
  32. 211 211
      CSharp/Game/Model/Component/EventComponent.cs
  33. 46 46
      CSharp/Game/Model/Component/FactoryComponent.cs
  34. 110 110
      CSharp/Game/Model/Component/GateNetworkComponent.cs
  35. 72 72
      CSharp/Game/Model/Component/MessageComponent.cs
  36. 207 207
      CSharp/Game/Model/Component/NetworkComponent.cs
  37. 88 88
      CSharp/Game/Model/Component/TimerComponent.cs
  38. 69 69
      CSharp/Game/Model/Component/UnitComponent.cs
  39. 17 17
      CSharp/Game/Model/Config/BuffConfig.cs
  40. 6 6
      CSharp/Game/Model/Config/GlobalConfig.cs
  41. 10 10
      CSharp/Game/Model/Config/ServerInfoConfig.cs
  42. 6 6
      CSharp/Game/Model/Config/UnitConfig.cs
  43. 23 23
      CSharp/Game/Model/ConfigAttribute.cs
  44. 7 7
      CSharp/Game/Model/Env.cs
  45. 17 17
      CSharp/Game/Model/EnvKey.cs
  46. 9 9
      CSharp/Game/Model/EventAttribute.cs
  47. 11 11
      CSharp/Game/Model/EventType.cs
  48. 16 16
      CSharp/Game/Model/FactoryAttribute.cs
  49. 26 26
      CSharp/Game/Model/GameException.cs
  50. 11 11
      CSharp/Game/Model/IAssemblyLoader.cs
  51. 9 9
      CSharp/Game/Model/ICategory.cs
  52. 8 8
      CSharp/Game/Model/IConfigLoader.cs
  53. 8 8
      CSharp/Game/Model/IFactory.cs
  54. 9 9
      CSharp/Game/Model/IStart.cs
  55. 9 9
      CSharp/Game/Model/IUpdate.cs
  56. 25 25
      CSharp/Game/Model/MessageAttribute.cs
  57. 119 119
      CSharp/Game/Model/Model.csproj
  58. 5 5
      CSharp/Game/Model/NumDefine.cs
  59. 8 8
      CSharp/Game/Model/Opcode.cs
  60. 42 42
      CSharp/Game/Model/Options.cs
  61. 38 38
      CSharp/Game/Model/Properties/AssemblyInfo.cs
  62. 13 13
      CSharp/Game/Model/ServerType.cs
  63. 24 24
      CSharp/Game/Model/Unit.cs
  64. 9 9
      CSharp/Game/Model/UnitType.cs
  65. 81 81
      CSharp/Game/Model/World.cs
  66. 35 35
      CSharp/Platform/Common/Base/Component.cs
  67. 118 118
      CSharp/Platform/Common/Base/Entity.cs
  68. 119 119
      CSharp/Platform/Common/Base/MultiMap.cs
  69. 119 119
      CSharp/Platform/Common/Base/Object.cs
  70. 46 46
      CSharp/Platform/Common/Base/QueueDictionary.cs
  71. 88 88
      CSharp/Platform/Common/Base/TimerManager.cs
  72. 87 87
      CSharp/Platform/Common/Common.csproj
  73. 79 79
      CSharp/Platform/Common/Helper/BigIntegerHelper.cs
  74. 34 34
      CSharp/Platform/Common/Helper/ByteHelper.cs
  75. 25 25
      CSharp/Platform/Common/Helper/EnumHelper.cs
  76. 19 19
      CSharp/Platform/Common/Helper/LoaderHelper.cs
  77. 64 64
      CSharp/Platform/Common/Helper/MongoHelper.cs
  78. 4 4
      CSharp/Platform/Common/Helper/Packages.config
  79. 49 49
      CSharp/Platform/Common/Helper/ProtobufHelper.cs
  80. 14 14
      CSharp/Platform/Common/Helper/RandomHelper.cs
  81. 39 39
      CSharp/Platform/Common/Helper/StringHelper.cs
  82. 12 12
      CSharp/Platform/Common/Helper/TimeHelper.cs
  83. 41 41
      CSharp/Platform/Common/Helper/XmlHelper.cs
  84. 21 21
      CSharp/Platform/Common/Hooks/Native.cs
  85. 39 39
      CSharp/Platform/Common/Logger/ALogDecorater.cs
  86. 7 7
      CSharp/Platform/Common/Logger/ILog.cs
  87. 34 34
      CSharp/Platform/Common/Logger/Log.cs
  88. 22 22
      CSharp/Platform/Common/Logger/NLogAdapter.cs
  89. 46 46
      CSharp/Platform/Common/Logger/StackInfoDecorater.cs
  90. 60 60
      CSharp/Platform/Common/Network/AChannel.cs
  91. 35 35
      CSharp/Platform/Common/Network/IService.cs
  92. 38 38
      CSharp/Platform/Common/Properties/AssemblyInfo.cs
  93. 47 47
      CSharp/Platform/ENet/ENet.vcxproj.filters
  94. 10 10
      CSharp/Platform/TNet/IPoller.cs
  95. 76 76
      CSharp/Platform/TNet/PacketParser.cs
  96. 38 38
      CSharp/Platform/TNet/Properties/AssemblyInfo.cs
  97. 121 121
      CSharp/Platform/TNet/TBuffer.cs
  98. 230 230
      CSharp/Platform/TNet/TChannel.cs
  99. 64 64
      CSharp/Platform/TNet/TNet.csproj
  100. 37 37
      CSharp/Platform/TNet/TPoller.cs

+ 139 - 139
CSharp/CSharp.sln

@@ -1,139 +1,139 @@
-
-Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.23107.0
-MinimumVisualStudioVersion = 10.0.40219.1
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{EAEF8202-B3F6-4F9B-9EFD-41C374433612}"
-	ProjectSection(SolutionItems) = preProject
-		.nuget\NuGet.Config = .nuget\NuGet.Config
-		.nuget\NuGet.exe = .nuget\NuGet.exe
-		.nuget\NuGet.targets = .nuget\NuGet.targets
-	EndProjectSection
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Platform", "Platform", "{ADBF5F67-B480-4A93-9D50-C81856FC61A9}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "App", "App", "{6E9D97F0-4243-452E-B832-1A855B8118EB}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Editor", "App\Editor\Editor.csproj", "{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure", "App\Infrastructure\Infrastructure.csproj", "{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Game", "Game", "{D0CC1FF4-2747-4278-A51F-BE9AA959175B}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BehaviorTreeModule", "App\Modules\BehaviorTreeModule\BehaviorTreeModule.csproj", "{6CD185D1-08E0-4729-A999-2D5B57BA8193}"
-EndProject
-Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ENet", "Platform\ENet\ENet.vcxproj", "{C9992B7C-313E-4C9F-A954-640D01EDFB58}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Platform\Common\Common.csproj", "{F06B995E-6508-4C5C-A396-554316C9215D}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TNet", "Platform\TNet\TNet.csproj", "{B1B78524-3F75-40D7-BF12-10B25A00C590}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UNet", "Platform\UNet\UNet.csproj", "{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Controller", "Game\Controller\Controller.csproj", "{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Game\Model\Model.csproj", "{0608C0C1-F584-4092-AAF9-1E99A78E3703}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{6A76F49C-07DC-4A7E-954F-7A7D3D900ED5}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Profile", "Exe\Profile\Profile.csproj", "{EA0D6994-A254-4DFE-9ADC-A29B7005419F}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ThirdParty", "ThirdParty", "{C189FE4B-3358-4C11-B120-AEC5971E7331}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nuget", "ThirdParty\Nuget\Nuget.csproj", "{56936640-F541-4389-9A0C-D8F6EB48427D}"
-EndProject
-Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{F13D0B3D-5B4F-452A-9378-0FD39555371D}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelTest", "Test\ModelTest\ModelTest.csproj", "{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TNetTest", "Test\TNetTest\TNetTest.csproj", "{1888D319-0495-43F3-BA8D-163EC20D9437}"
-EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UNetTest", "Test\UNetTest\UNetTest.csproj", "{47A7404D-F501-43C5-8183-4B4E9E8C24B2}"
-EndProject
-Global
-	GlobalSection(SolutionConfigurationPlatforms) = preSolution
-		Debug|Any CPU = Debug|Any CPU
-		Release|Any CPU = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Release|Any CPU.ActiveCfg = Release|x86
-		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Release|Any CPU.Build.0 = Release|x86
-		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Release|Any CPU.Build.0 = Release|Any CPU
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Any CPU.Build.0 = Release|Any CPU
-		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Debug|Any CPU.ActiveCfg = Debug|Win32
-		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Debug|Any CPU.Build.0 = Debug|Win32
-		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Release|Any CPU.ActiveCfg = Release|Win32
-		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Release|Any CPU.Build.0 = Release|Win32
-		{F06B995E-6508-4C5C-A396-554316C9215D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{F06B995E-6508-4C5C-A396-554316C9215D}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{F06B995E-6508-4C5C-A396-554316C9215D}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{F06B995E-6508-4C5C-A396-554316C9215D}.Release|Any CPU.Build.0 = Release|Any CPU
-		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Release|Any CPU.Build.0 = Release|Any CPU
-		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Release|Any CPU.Build.0 = Release|Any CPU
-		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Release|Any CPU.Build.0 = Release|Any CPU
-		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Release|Any CPU.Build.0 = Release|Any CPU
-		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Release|Any CPU.Build.0 = Release|Any CPU
-		{56936640-F541-4389-9A0C-D8F6EB48427D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{56936640-F541-4389-9A0C-D8F6EB48427D}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{56936640-F541-4389-9A0C-D8F6EB48427D}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{56936640-F541-4389-9A0C-D8F6EB48427D}.Release|Any CPU.Build.0 = Release|Any CPU
-		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Release|Any CPU.Build.0 = Release|Any CPU
-		{1888D319-0495-43F3-BA8D-163EC20D9437}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{1888D319-0495-43F3-BA8D-163EC20D9437}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{1888D319-0495-43F3-BA8D-163EC20D9437}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{1888D319-0495-43F3-BA8D-163EC20D9437}.Release|Any CPU.Build.0 = Release|Any CPU
-		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
-		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
-		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
-		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Release|Any CPU.Build.0 = Release|Any CPU
-	EndGlobalSection
-	GlobalSection(SolutionProperties) = preSolution
-		HideSolutionNode = FALSE
-	EndGlobalSection
-	GlobalSection(NestedProjects) = preSolution
-		{C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
-		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
-		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
-		{6CD185D1-08E0-4729-A999-2D5B57BA8193} = {C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6}
-		{C9992B7C-313E-4C9F-A954-640D01EDFB58} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
-		{F06B995E-6508-4C5C-A396-554316C9215D} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
-		{B1B78524-3F75-40D7-BF12-10B25A00C590} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
-		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
-		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
-		{0608C0C1-F584-4092-AAF9-1E99A78E3703} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
-		{EA0D6994-A254-4DFE-9ADC-A29B7005419F} = {6A76F49C-07DC-4A7E-954F-7A7D3D900ED5}
-		{56936640-F541-4389-9A0C-D8F6EB48427D} = {C189FE4B-3358-4C11-B120-AEC5971E7331}
-		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
-		{1888D319-0495-43F3-BA8D-163EC20D9437} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
-		{47A7404D-F501-43C5-8183-4B4E9E8C24B2} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
-	EndGlobalSection
-EndGlobal
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.23107.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Modules", "Modules", "{C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{EAEF8202-B3F6-4F9B-9EFD-41C374433612}"
+	ProjectSection(SolutionItems) = preProject
+		.nuget\NuGet.Config = .nuget\NuGet.Config
+		.nuget\NuGet.exe = .nuget\NuGet.exe
+		.nuget\NuGet.targets = .nuget\NuGet.targets
+	EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Platform", "Platform", "{ADBF5F67-B480-4A93-9D50-C81856FC61A9}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "App", "App", "{6E9D97F0-4243-452E-B832-1A855B8118EB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Editor", "App\Editor\Editor.csproj", "{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Infrastructure", "App\Infrastructure\Infrastructure.csproj", "{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Game", "Game", "{D0CC1FF4-2747-4278-A51F-BE9AA959175B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BehaviorTreeModule", "App\Modules\BehaviorTreeModule\BehaviorTreeModule.csproj", "{6CD185D1-08E0-4729-A999-2D5B57BA8193}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ENet", "Platform\ENet\ENet.vcxproj", "{C9992B7C-313E-4C9F-A954-640D01EDFB58}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Common", "Platform\Common\Common.csproj", "{F06B995E-6508-4C5C-A396-554316C9215D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TNet", "Platform\TNet\TNet.csproj", "{B1B78524-3F75-40D7-BF12-10B25A00C590}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UNet", "Platform\UNet\UNet.csproj", "{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Controller", "Game\Controller\Controller.csproj", "{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Game\Model\Model.csproj", "{0608C0C1-F584-4092-AAF9-1E99A78E3703}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Exe", "Exe", "{6A76F49C-07DC-4A7E-954F-7A7D3D900ED5}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Profile", "Exe\Profile\Profile.csproj", "{EA0D6994-A254-4DFE-9ADC-A29B7005419F}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ThirdParty", "ThirdParty", "{C189FE4B-3358-4C11-B120-AEC5971E7331}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nuget", "ThirdParty\Nuget\Nuget.csproj", "{56936640-F541-4389-9A0C-D8F6EB48427D}"
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{F13D0B3D-5B4F-452A-9378-0FD39555371D}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelTest", "Test\ModelTest\ModelTest.csproj", "{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TNetTest", "Test\TNetTest\TNetTest.csproj", "{1888D319-0495-43F3-BA8D-163EC20D9437}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UNetTest", "Test\UNetTest\UNetTest.csproj", "{47A7404D-F501-43C5-8183-4B4E9E8C24B2}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Release|Any CPU.ActiveCfg = Release|x86
+		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0}.Release|Any CPU.Build.0 = Release|x86
+		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3}.Release|Any CPU.Build.0 = Release|Any CPU
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Any CPU.Build.0 = Release|Any CPU
+		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Debug|Any CPU.ActiveCfg = Debug|Win32
+		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Debug|Any CPU.Build.0 = Debug|Win32
+		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Release|Any CPU.ActiveCfg = Release|Win32
+		{C9992B7C-313E-4C9F-A954-640D01EDFB58}.Release|Any CPU.Build.0 = Release|Win32
+		{F06B995E-6508-4C5C-A396-554316C9215D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{F06B995E-6508-4C5C-A396-554316C9215D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{F06B995E-6508-4C5C-A396-554316C9215D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{F06B995E-6508-4C5C-A396-554316C9215D}.Release|Any CPU.Build.0 = Release|Any CPU
+		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{B1B78524-3F75-40D7-BF12-10B25A00C590}.Release|Any CPU.Build.0 = Release|Any CPU
+		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}.Release|Any CPU.Build.0 = Release|Any CPU
+		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}.Release|Any CPU.Build.0 = Release|Any CPU
+		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{0608C0C1-F584-4092-AAF9-1E99A78E3703}.Release|Any CPU.Build.0 = Release|Any CPU
+		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{EA0D6994-A254-4DFE-9ADC-A29B7005419F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{56936640-F541-4389-9A0C-D8F6EB48427D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{56936640-F541-4389-9A0C-D8F6EB48427D}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{56936640-F541-4389-9A0C-D8F6EB48427D}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{56936640-F541-4389-9A0C-D8F6EB48427D}.Release|Any CPU.Build.0 = Release|Any CPU
+		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35}.Release|Any CPU.Build.0 = Release|Any CPU
+		{1888D319-0495-43F3-BA8D-163EC20D9437}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{1888D319-0495-43F3-BA8D-163EC20D9437}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{1888D319-0495-43F3-BA8D-163EC20D9437}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{1888D319-0495-43F3-BA8D-163EC20D9437}.Release|Any CPU.Build.0 = Release|Any CPU
+		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{47A7404D-F501-43C5-8183-4B4E9E8C24B2}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(NestedProjects) = preSolution
+		{C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
+		{C46F3337-0F48-4A72-84AD-8FDD1F159BB0} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
+		{48A2E149-0DAC-41B4-BB54-DFBCCD6D42B3} = {6E9D97F0-4243-452E-B832-1A855B8118EB}
+		{6CD185D1-08E0-4729-A999-2D5B57BA8193} = {C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6}
+		{C9992B7C-313E-4C9F-A954-640D01EDFB58} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
+		{F06B995E-6508-4C5C-A396-554316C9215D} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
+		{B1B78524-3F75-40D7-BF12-10B25A00C590} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
+		{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E} = {ADBF5F67-B480-4A93-9D50-C81856FC61A9}
+		{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
+		{0608C0C1-F584-4092-AAF9-1E99A78E3703} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
+		{EA0D6994-A254-4DFE-9ADC-A29B7005419F} = {6A76F49C-07DC-4A7E-954F-7A7D3D900ED5}
+		{56936640-F541-4389-9A0C-D8F6EB48427D} = {C189FE4B-3358-4C11-B120-AEC5971E7331}
+		{DEF89A61-8AC7-4CCD-80B8-FC6AA2571E35} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
+		{1888D319-0495-43F3-BA8D-163EC20D9437} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
+		{47A7404D-F501-43C5-8183-4B4E9E8C24B2} = {F13D0B3D-5B4F-452A-9378-0FD39555371D}
+	EndGlobalSection
+EndGlobal

+ 6 - 6
CSharp/Exe/Profile/App.config

@@ -1,6 +1,6 @@
-<?xml version="1.0" encoding="utf-8"?>
-<configuration>
-    <startup> 
-        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
-    </startup>
-</configuration>
+<?xml version="1.0" encoding="utf-8"?>
+<configuration>
+    <startup> 
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
+    </startup>
+</configuration>

+ 72 - 72
CSharp/Exe/Profile/Profile.csproj

@@ -1,73 +1,73 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProjectGuid>{EA0D6994-A254-4DFE-9ADC-A29B7005419F}</ProjectGuid>
-    <OutputType>Exe</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>Profile</RootNamespace>
-    <AssemblyName>Profile</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-    <TargetFrameworkProfile />
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <PlatformTarget>AnyCPU</PlatformTarget>
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>..\..\Bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <PlatformTarget>AnyCPU</PlatformTarget>
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>..\..\Bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-    <Reference Include="System.Xml.Linq" />
-    <Reference Include="System.Data.DataSetExtensions" />
-    <Reference Include="Microsoft.CSharp" />
-    <Reference Include="System.Data" />
-    <Reference Include="System.Xml" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="Program.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="App.config" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
-      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
-      <Name>Common</Name>
-    </ProjectReference>
-    <ProjectReference Include="..\..\Test\TNetTest\TNetTest.csproj">
-      <Project>{1888D319-0495-43F3-BA8D-163EC20D9437}</Project>
-      <Name>TNetTest</Name>
-    </ProjectReference>
-    <ProjectReference Include="..\..\Test\UNetTest\UNetTest.csproj">
-      <Project>{47A7404D-F501-43C5-8183-4B4E9E8C24B2}</Project>
-      <Name>UNetTest</Name>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{EA0D6994-A254-4DFE-9ADC-A29B7005419F}</ProjectGuid>
+    <OutputType>Exe</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Profile</RootNamespace>
+    <AssemblyName>Profile</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <PlatformTarget>AnyCPU</PlatformTarget>
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Xml.Linq" />
+    <Reference Include="System.Data.DataSetExtensions" />
+    <Reference Include="Microsoft.CSharp" />
+    <Reference Include="System.Data" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Program.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="App.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
+      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\Test\TNetTest\TNetTest.csproj">
+      <Project>{1888D319-0495-43F3-BA8D-163EC20D9437}</Project>
+      <Name>TNetTest</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\Test\UNetTest\UNetTest.csproj">
+      <Project>{47A7404D-F501-43C5-8183-4B4E9E8C24B2}</Project>
+      <Name>UNetTest</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
 </Project>

+ 15 - 15
CSharp/Exe/Profile/Program.cs

@@ -1,16 +1,16 @@
-using Common.Logger;
-using TNetTest;
-
-namespace Profile
-{
-	internal static class Program
-	{
-		private static void Main(string[] args)
-		{
-			TServiceTest test = new TServiceTest();
-			Log.Debug("Profile start");
-			test.ClientSendToServer();
-			Log.Debug("Profile stop");
-		}
-	}
+using Common.Logger;
+using TNetTest;
+
+namespace Profile
+{
+	internal static class Program
+	{
+		private static void Main(string[] args)
+		{
+			TServiceTest test = new TServiceTest();
+			Log.Debug("Profile start");
+			test.ClientSendToServer();
+			Log.Debug("Profile stop");
+		}
+	}
 }

+ 38 - 38
CSharp/Exe/Profile/Properties/AssemblyInfo.cs

@@ -1,39 +1,39 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Profile")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Profile")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("784e44fc-7993-457c-ab57-28b174b9bca5")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过以下
+// 特性集控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("Profile")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("Profile")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 使此程序集中的类型
+// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+// 则将该类型上的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("784e44fc-7993-457c-ab57-28b174b9bca5")]
+
+// 程序集的版本信息由下面四个值组成: 
+//
+//      主版本
+//      次版本 
+//      生成号
+//      修订号
+//
+// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: 
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

+ 16 - 16
CSharp/Game/Controller/BehaviorTreeNode/Not.cs

@@ -1,17 +1,17 @@
-using Model;
-
-namespace Controller
-{
-	[Node(NodeType.Not)]
-	public class Not: Node
-	{
-		public Not(NodeConfig config): base(config)
-		{
-		}
-
-		public override bool Run(Env env)
-		{
-			return !this.children[0].Run(env);
-		}
-	}
+using Model;
+
+namespace Controller
+{
+	[Node(NodeType.Not)]
+	public class Not: Node
+	{
+		public Not(NodeConfig config): base(config)
+		{
+		}
+
+		public override bool Run(Env env)
+		{
+			return !this.children[0].Run(env);
+		}
+	}
 }

+ 23 - 23
CSharp/Game/Controller/BehaviorTreeNode/Selector.cs

@@ -1,24 +1,24 @@
-using Model;
-
-namespace Controller
-{
-	[Node(NodeType.Selector)]
-	public class Selector: Node
-	{
-		public Selector(NodeConfig config): base(config)
-		{
-		}
-
-		public override bool Run(Env env)
-		{
-			foreach (var child in this.children)
-			{
-				if (child.Run(env))
-				{
-					return true;
-				}
-			}
-			return false;
-		}
-	}
+using Model;
+
+namespace Controller
+{
+	[Node(NodeType.Selector)]
+	public class Selector: Node
+	{
+		public Selector(NodeConfig config): base(config)
+		{
+		}
+
+		public override bool Run(Env env)
+		{
+			foreach (var child in this.children)
+			{
+				if (child.Run(env))
+				{
+					return true;
+				}
+			}
+			return false;
+		}
+	}
 }

+ 23 - 23
CSharp/Game/Controller/BehaviorTreeNode/Sequence.cs

@@ -1,24 +1,24 @@
-using Model;
-
-namespace Controller
-{
-	[Node(NodeType.Sequence)]
-	internal class Sequence: Node
-	{
-		public Sequence(NodeConfig config): base(config)
-		{
-		}
-
-		public override bool Run(Env env)
-		{
-			foreach (var child in this.children)
-			{
-				if (!child.Run(env))
-				{
-					return false;
-				}
-			}
-			return true;
-		}
-	}
+using Model;
+
+namespace Controller
+{
+	[Node(NodeType.Sequence)]
+	internal class Sequence: Node
+	{
+		public Sequence(NodeConfig config): base(config)
+		{
+		}
+
+		public override bool Run(Env env)
+		{
+			foreach (var child in this.children)
+			{
+				if (!child.Run(env))
+				{
+					return false;
+				}
+			}
+			return true;
+		}
+	}
 }

+ 8 - 8
CSharp/Game/Controller/ConfigCategory/BuffCategory.cs

@@ -1,9 +1,9 @@
-using Model;
-
-namespace Controller
-{
-	[Config(ServerType.City)]
-	public class BuffCategory: ACategory<BuffConfig>
-	{
-	}
+using Model;
+
+namespace Controller
+{
+	[Config(ServerType.City)]
+	public class BuffCategory: ACategory<BuffConfig>
+	{
+	}
 }

+ 8 - 8
CSharp/Game/Controller/ConfigCategory/GlobalCategory.cs

@@ -1,9 +1,9 @@
-using Model;
-
-namespace Controller
-{
-	[Config(ServerType.All)]
-	public class GlobalCategory: ACategory<GlobalConfig>
-	{
-	}
+using Model;
+
+namespace Controller
+{
+	[Config(ServerType.All)]
+	public class GlobalCategory: ACategory<GlobalConfig>
+	{
+	}
 }

+ 29 - 29
CSharp/Game/Controller/ConfigCategory/ServerInfoCategory.cs

@@ -1,30 +1,30 @@
-using System.Collections.Generic;
-using Model;
-
-namespace Controller
-{
-	[Config(ServerType.All)]
-	public class ServerInfoCategory: ACategory<ServerInfoConfig>
-	{
-		public Dictionary<string, ServerInfoConfig> NameServerInfoConfigs =
-				new Dictionary<string, ServerInfoConfig>();
-
-		public override void EndInit()
-		{
-			base.EndInit();
-
-			foreach (ServerInfoConfig serverInfoConfig in this.GetAll())
-			{
-				this.NameServerInfoConfigs[serverInfoConfig.Name] = serverInfoConfig;
-			}
-		}
-
-		public ServerInfoConfig this[string name]
-		{
-			get
-			{
-				return this.NameServerInfoConfigs[name];
-			}
-		}
-	}
+using System.Collections.Generic;
+using Model;
+
+namespace Controller
+{
+	[Config(ServerType.All)]
+	public class ServerInfoCategory: ACategory<ServerInfoConfig>
+	{
+		public Dictionary<string, ServerInfoConfig> NameServerInfoConfigs =
+				new Dictionary<string, ServerInfoConfig>();
+
+		public override void EndInit()
+		{
+			base.EndInit();
+
+			foreach (ServerInfoConfig serverInfoConfig in this.GetAll())
+			{
+				this.NameServerInfoConfigs[serverInfoConfig.Name] = serverInfoConfig;
+			}
+		}
+
+		public ServerInfoConfig this[string name]
+		{
+			get
+			{
+				return this.NameServerInfoConfigs[name];
+			}
+		}
+	}
 }

+ 8 - 8
CSharp/Game/Controller/ConfigCategory/UnitCategory.cs

@@ -1,9 +1,9 @@
-using Model;
-
-namespace Controller
-{
-	[Config(ServerType.All)]
-	public class UnitCategory: ACategory<UnitConfig>
-	{
-	}
+using Model;
+
+namespace Controller
+{
+	[Config(ServerType.All)]
+	public class UnitCategory: ACategory<UnitConfig>
+	{
+	}
 }

+ 81 - 81
CSharp/Game/Controller/Controller.csproj

@@ -1,82 +1,82 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProjectGuid>{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}</ProjectGuid>
-    <OutputType>Library</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>Controller</RootNamespace>
-    <AssemblyName>Controller</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-    <TargetFrameworkProfile />
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>..\..\Bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>..\..\Bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
-      <Private>True</Private>
-    </Reference>
-    <Reference Include="NLog, Version=4.1.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
-      <HintPath>..\..\packages\NLog.4.1.0\lib\net45\NLog.dll</HintPath>
-      <Private>True</Private>
-    </Reference>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="Logic\AddressHelper.cs" />
-    <Compile Include="ConfigCategory\TreeCategory.cs" />
-    <Compile Include="Event\SleepTimeoutEvent.cs" />
-    <Compile Include="Event\BuffTimeoutEvent.cs" />
-    <Compile Include="BehaviorTreeNode\Not.cs" />
-    <Compile Include="BehaviorTreeNode\Selector.cs" />
-    <Compile Include="BehaviorTreeNode\Sequence.cs" />
-    <Compile Include="ConfigCategory\BuffCategory.cs" />
-    <Compile Include="ConfigCategory\GlobalCategory.cs" />
-    <Compile Include="ConfigCategory\ServerInfoCategory.cs" />
-    <Compile Include="ConfigCategory\UnitCategory.cs" />
-    <Compile Include="Factory\UnitPlayerFactory.cs" />
-    <Compile Include="Message\CMsgLoginEvent.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
-      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
-      <Name>Common</Name>
-    </ProjectReference>
-    <ProjectReference Include="..\Model\Model.csproj">
-      <Project>{0608C0C1-F584-4092-AAF9-1E99A78E3703}</Project>
-      <Name>Model</Name>
-    </ProjectReference>
-  </ItemGroup>
-  <ItemGroup>
-    <Folder Include="Extension\" />
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{7D5B90DF-43AC-42B8-9A52-2B985BC42A5C}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Controller</RootNamespace>
+    <AssemblyName>Controller</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="NLog, Version=4.1.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
+      <HintPath>..\..\packages\NLog.4.1.0\lib\net45\NLog.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Logic\AddressHelper.cs" />
+    <Compile Include="ConfigCategory\TreeCategory.cs" />
+    <Compile Include="Event\SleepTimeoutEvent.cs" />
+    <Compile Include="Event\BuffTimeoutEvent.cs" />
+    <Compile Include="BehaviorTreeNode\Not.cs" />
+    <Compile Include="BehaviorTreeNode\Selector.cs" />
+    <Compile Include="BehaviorTreeNode\Sequence.cs" />
+    <Compile Include="ConfigCategory\BuffCategory.cs" />
+    <Compile Include="ConfigCategory\GlobalCategory.cs" />
+    <Compile Include="ConfigCategory\ServerInfoCategory.cs" />
+    <Compile Include="ConfigCategory\UnitCategory.cs" />
+    <Compile Include="Factory\UnitPlayerFactory.cs" />
+    <Compile Include="Message\CMsgLoginEvent.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
+      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\Model\Model.csproj">
+      <Project>{0608C0C1-F584-4092-AAF9-1E99A78E3703}</Project>
+      <Name>Model</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Extension\" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
 </Project>

+ 18 - 18
CSharp/Game/Controller/Event/BuffTimeoutEvent.cs

@@ -1,19 +1,19 @@
-using Model;
-using MongoDB.Bson;
-
-namespace Controller
-{
-	[Event(EventType.BuffTimeout, ServerType.City)]
-	public class BuffTimeoutEvent: AEvent<Env>
-	{
-		public override void Run(Env env)
-		{
-			Unit owner = World.Instance.GetComponent<UnitComponent>().Get(env.Get<ObjectId>(EnvKey.OwnerId));
-			if (owner == null)
-			{
-				return;
-			}
-			owner.GetComponent<BuffComponent>().RemoveById(env.Get<ObjectId>(EnvKey.BuffId));
-		}
-	}
+using Model;
+using MongoDB.Bson;
+
+namespace Controller
+{
+	[Event(EventType.BuffTimeout, ServerType.City)]
+	public class BuffTimeoutEvent: AEvent<Env>
+	{
+		public override void Run(Env env)
+		{
+			Unit owner = World.Instance.GetComponent<UnitComponent>().Get(env.Get<ObjectId>(EnvKey.OwnerId));
+			if (owner == null)
+			{
+				return;
+			}
+			owner.GetComponent<BuffComponent>().RemoveById(env.Get<ObjectId>(EnvKey.BuffId));
+		}
+	}
 }

+ 14 - 14
CSharp/Game/Controller/Factory/UnitPlayerFactory.cs

@@ -1,15 +1,15 @@
-using Model;
-
-namespace Controller
-{
-	[Factory(typeof (Unit), UnitType.GatePlayer)]
-	public class UnitGatePlayerFactory: IFactory<Unit>
-	{
-		public Unit Create(int configId)
-		{
-			Unit gatePlayer = new Unit(configId);
-			World.Instance.GetComponent<UnitComponent>().Add(gatePlayer);
-			return gatePlayer;
-		}
-	}
+using Model;
+
+namespace Controller
+{
+	[Factory(typeof (Unit), UnitType.GatePlayer)]
+	public class UnitGatePlayerFactory: IFactory<Unit>
+	{
+		public Unit Create(int configId)
+		{
+			Unit gatePlayer = new Unit(configId);
+			World.Instance.GetComponent<UnitComponent>().Add(gatePlayer);
+			return gatePlayer;
+		}
+	}
 }

+ 19 - 19
CSharp/Game/Controller/Message/CMsgLoginEvent.cs

@@ -1,20 +1,20 @@
-using System.Threading.Tasks;
-using Model;
-
-namespace Controller
-{
-	public class CMsgLogin
-	{
-		public byte[] Account { get; set; }
-		public byte[] PassMd5 { get; set; }
-	}
-
-	[Message(ServerType.Gate)]
-	internal class CMsgLoginEvent : MEvent<CMsgLogin, Task<bool>>
-	{
-		public override async Task<bool> Run(CMsgLogin msg)
-		{
-			return true;
-		}
-	}
+using System.Threading.Tasks;
+using Model;
+
+namespace Controller
+{
+	public class CMsgLogin
+	{
+		public byte[] Account { get; set; }
+		public byte[] PassMd5 { get; set; }
+	}
+
+	[Message(ServerType.Gate)]
+	internal class CMsgLoginEvent : MEvent<CMsgLogin, Task<bool>>
+	{
+		public override async Task<bool> Run(CMsgLogin msg)
+		{
+			return true;
+		}
+	}
 }

+ 38 - 38
CSharp/Game/Controller/Properties/AssemblyInfo.cs

@@ -1,39 +1,39 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Controller")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Controller")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("d9d1f906-81a1-48c8-b901-93e2aede657c")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过以下
+// 特性集控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("Controller")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("Controller")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 使此程序集中的类型
+// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+// 则将该类型上的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("d9d1f906-81a1-48c8-b901-93e2aede657c")]
+
+// 程序集的版本信息由下面四个值组成: 
+//
+//      主版本
+//      次版本 
+//      生成号
+//      修订号
+//
+// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: 
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

+ 55 - 55
CSharp/Game/Model/ACategory.cs

@@ -1,56 +1,56 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using Common.Helper;
-
-namespace Model
-{
-	public abstract class ACategory<T>: ICategory where T : AConfig
-	{
-		private Dictionary<int, T> dict;
-
-		public virtual void BeginInit()
-		{
-			this.dict = new Dictionary<int, T>();
-
-			string path = Path.Combine(@"../../Config/", typeof (T).Name);
-
-			if (!Directory.Exists(path))
-			{
-				throw new Exception($"not found config path: {path}");
-			}
-
-			foreach (string file in Directory.GetFiles(path))
-			{
-				T t = MongoHelper.FromJson<T>(File.ReadAllText(file));
-				this.dict.Add(t.Id, t);
-			}
-		}
-
-		public Type ConfigType
-		{
-			get
-			{
-				return typeof (T);
-			}
-		}
-
-		public virtual void EndInit()
-		{
-		}
-
-		public T this[int type]
-		{
-			get
-			{
-				return this.dict[type];
-			}
-		}
-
-		public T[] GetAll()
-		{
-			return this.dict.Values.ToArray();
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Common.Helper;
+
+namespace Model
+{
+	public abstract class ACategory<T>: ICategory where T : AConfig
+	{
+		private Dictionary<int, T> dict;
+
+		public virtual void BeginInit()
+		{
+			this.dict = new Dictionary<int, T>();
+
+			string path = Path.Combine(@"../../Config/", typeof (T).Name);
+
+			if (!Directory.Exists(path))
+			{
+				throw new Exception($"not found config path: {path}");
+			}
+
+			foreach (string file in Directory.GetFiles(path))
+			{
+				T t = MongoHelper.FromJson<T>(File.ReadAllText(file));
+				this.dict.Add(t.Id, t);
+			}
+		}
+
+		public Type ConfigType
+		{
+			get
+			{
+				return typeof (T);
+			}
+		}
+
+		public virtual void EndInit()
+		{
+		}
+
+		public T this[int type]
+		{
+			get
+			{
+				return this.dict[type];
+			}
+		}
+
+		public T[] GetAll()
+		{
+			return this.dict.Values.ToArray();
+		}
+	}
 }

+ 18 - 18
CSharp/Game/Model/AConfig.cs

@@ -1,19 +1,19 @@
-using System.ComponentModel;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Model
-{
-	public abstract class AConfig: ISupportInitialize
-	{
-		[BsonId]
-		public int Id { get; set; }
-
-		public virtual void BeginInit()
-		{
-		}
-
-		public virtual void EndInit()
-		{
-		}
-	}
+using System.ComponentModel;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Model
+{
+	public abstract class AConfig: ISupportInitialize
+	{
+		[BsonId]
+		public int Id { get; set; }
+
+		public virtual void BeginInit()
+		{
+		}
+
+		public virtual void EndInit()
+		{
+		}
+	}
 }

+ 26 - 26
CSharp/Game/Model/AEventAttribute.cs

@@ -1,27 +1,27 @@
-using System;
-
-namespace Model
-{
-	[AttributeUsage(AttributeTargets.Class)]
-	public abstract class AEventAttribute: Attribute
-	{
-		public EventType Type { get; private set; }
-
-		private ServerType ServerType { get; set; }
-
-		protected AEventAttribute(EventType type, ServerType serverType)
-		{
-			this.Type = type;
-			this.ServerType = serverType;
-		}
-
-		public bool Contains(ServerType serverType)
-		{
-			if ((this.ServerType & serverType) == 0)
-			{
-				return false;
-			}
-			return true;
-		}
-	}
+using System;
+
+namespace Model
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public abstract class AEventAttribute: Attribute
+	{
+		public EventType Type { get; private set; }
+
+		private ServerType ServerType { get; set; }
+
+		protected AEventAttribute(EventType type, ServerType serverType)
+		{
+			this.Type = type;
+			this.ServerType = serverType;
+		}
+
+		public bool Contains(ServerType serverType)
+		{
+			if ((this.ServerType & serverType) == 0)
+			{
+				return false;
+			}
+			return true;
+		}
+	}
 }

+ 70 - 70
CSharp/Game/Model/Actor.cs

@@ -1,71 +1,71 @@
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Common.Base;
-using Common.Logger;
-using MongoDB.Bson;
-
-namespace Model
-{
-	public class Actor : Entity<Unit>, IDisposable
-	{
-		private readonly Queue<byte[]> msgQueue = new Queue<byte[]>();
-
-		private Action msgAction = () => { };
-		
-		private bool isStop;
-
-		public Actor(ObjectId id): base(id)
-		{
-			this.Start();
-		}
-
-		private async void Start()
-		{
-			while (!this.isStop)
-			{
-				try
-				{
-					byte[] messageBytes = await this.Get();
-					Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
-					await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, messageBytes);
-				}
-				catch (Exception e)
-				{
-					Log.Trace(e.ToString());
-				}
-			}
-		}
-
-		public void Add(byte[] msg)
-		{
-			this.msgQueue.Enqueue(msg);
-			this.msgAction();
-		}
-
-		private Task<byte[]> Get()
-		{
-			var tcs = new TaskCompletionSource<byte[]>();
-			if (this.msgQueue.Count > 0)
-			{
-				byte[] messageBytes = this.msgQueue.Dequeue();
-				tcs.SetResult(messageBytes);
-			}
-			else
-			{
-				this.msgAction = () =>
-				{
-					this.msgAction = () => { };
-					byte[] msg = this.msgQueue.Dequeue();
-					tcs.SetResult(msg);
-				};
-			}
-			return tcs.Task;
-		}
-
-		public void Dispose()
-		{
-			this.isStop = true;
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Common.Base;
+using Common.Logger;
+using MongoDB.Bson;
+
+namespace Model
+{
+	public class Actor : Entity<Unit>, IDisposable
+	{
+		private readonly Queue<byte[]> msgQueue = new Queue<byte[]>();
+
+		private Action msgAction = () => { };
+		
+		private bool isStop;
+
+		public Actor(ObjectId id): base(id)
+		{
+			this.Start();
+		}
+
+		private async void Start()
+		{
+			while (!this.isStop)
+			{
+				try
+				{
+					byte[] messageBytes = await this.Get();
+					Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
+					await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, messageBytes);
+				}
+				catch (Exception e)
+				{
+					Log.Trace(e.ToString());
+				}
+			}
+		}
+
+		public void Add(byte[] msg)
+		{
+			this.msgQueue.Enqueue(msg);
+			this.msgAction();
+		}
+
+		private Task<byte[]> Get()
+		{
+			var tcs = new TaskCompletionSource<byte[]>();
+			if (this.msgQueue.Count > 0)
+			{
+				byte[] messageBytes = this.msgQueue.Dequeue();
+				tcs.SetResult(messageBytes);
+			}
+			else
+			{
+				this.msgAction = () =>
+				{
+					this.msgAction = () => { };
+					byte[] msg = this.msgQueue.Dequeue();
+					tcs.SetResult(msg);
+				};
+			}
+			return tcs.Task;
+		}
+
+		public void Dispose()
+		{
+			this.isStop = true;
+		}
+	}
 }

+ 16 - 16
CSharp/Game/Model/BehaviorTree/BehaviorTree.cs

@@ -1,17 +1,17 @@
-namespace Model
-{
-	public class BehaviorTree
-	{
-		private readonly Node node;
-		
-		public BehaviorTree(Node node)
-		{
-			this.node = node;
-		}
-
-		public bool Run(Env env)
-		{
-			return this.node.Run(env);
-		}
-	}
+namespace Model
+{
+	public class BehaviorTree
+	{
+		private readonly Node node;
+		
+		public BehaviorTree(Node node)
+		{
+			this.node = node;
+		}
+
+		public bool Run(Env env)
+		{
+			return this.node.Run(env);
+		}
+	}
 }

+ 55 - 55
CSharp/Game/Model/BehaviorTree/Node.cs

@@ -1,56 +1,56 @@
-using System.Collections.Generic;
-
-namespace Model
-{
-	public abstract class Node
-	{
-		private readonly NodeConfig config;
-
-		protected readonly List<Node> children = new List<Node>();
-
-		protected Node(NodeConfig config)
-		{
-			this.config = config;
-		}
-
-		/// <summary>
-		/// 策划配置的id
-		/// </summary>
-		public int Id
-		{
-			get
-			{
-				return this.config.Id;
-			}
-		}
-
-		/// <summary>
-		/// 节点的类型例如: NodeType.Not
-		/// </summary>
-		public NodeType Type
-		{
-			get
-			{
-				return this.config.Type;
-			}
-		}
-
-		public List<string> Args
-		{
-			get
-			{
-				return this.config.Args;
-			}
-		}
-
-		public void AddChild(Node child)
-		{
-			this.children.Add(child);
-		}
-
-		public virtual bool Run(Env env)
-		{
-			return true;
-		}
-	}
+using System.Collections.Generic;
+
+namespace Model
+{
+	public abstract class Node
+	{
+		private readonly NodeConfig config;
+
+		protected readonly List<Node> children = new List<Node>();
+
+		protected Node(NodeConfig config)
+		{
+			this.config = config;
+		}
+
+		/// <summary>
+		/// 策划配置的id
+		/// </summary>
+		public int Id
+		{
+			get
+			{
+				return this.config.Id;
+			}
+		}
+
+		/// <summary>
+		/// 节点的类型例如: NodeType.Not
+		/// </summary>
+		public NodeType Type
+		{
+			get
+			{
+				return this.config.Type;
+			}
+		}
+
+		public List<string> Args
+		{
+			get
+			{
+				return this.config.Args;
+			}
+		}
+
+		public void AddChild(Node child)
+		{
+			this.children.Add(child);
+		}
+
+		public virtual bool Run(Env env)
+		{
+			return true;
+		}
+	}
 }

+ 14 - 14
CSharp/Game/Model/BehaviorTree/NodeAttribute.cs

@@ -1,15 +1,15 @@
-using System;
-
-namespace Model
-{
-	[AttributeUsage(AttributeTargets.Class)]
-	public class NodeAttribute: Attribute
-	{
-		public NodeType Type { get; private set; }
-
-		public NodeAttribute(NodeType type)
-		{
-			this.Type = type;
-		}
-	}
+using System;
+
+namespace Model
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class NodeAttribute: Attribute
+	{
+		public NodeType Type { get; private set; }
+
+		public NodeAttribute(NodeType type)
+		{
+			this.Type = type;
+		}
+	}
 }

+ 129 - 129
CSharp/Game/Model/Buff.cs

@@ -1,130 +1,130 @@
-using System;
-using Common.Base;
-using Common.Helper;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Model
-{
-	public class Buff: Entity<Buff>, IDisposable
-	{
-		[BsonElement]
-		private int configId { get; set; }
-
-		[BsonElement]
-		private ObjectId ownerId;
-
-		[BsonElement]
-		private long expiration;
-
-		[BsonIgnore]
-		private ObjectId timerId;
-
-		[BsonIgnore]
-		public long Expiration
-		{
-			get
-			{
-				return this.expiration;
-			}
-			set
-			{
-				this.expiration = value;
-			}
-		}
-
-		[BsonIgnore]
-		public ObjectId TimerId
-		{
-			get
-			{
-				return this.timerId;
-			}
-			set
-			{
-				this.timerId = value;
-			}
-		}
-
-		public Buff(int configId, ObjectId ownerId)
-		{
-			this.configId = configId;
-			this.ownerId = ownerId;
-			if (this.Config.Duration != 0)
-			{
-				this.Expiration = TimeHelper.Now() + this.Config.Duration;
-			}
-
-			if (this.Expiration != 0)
-			{
-				// 注册Timer回调
-				Env env = new Env();
-				env[EnvKey.OwnerId] = this.OwnerId;
-				env[EnvKey.BuffId] = this.Id;
-				this.TimerId = World.Instance.GetComponent<TimerComponent>()
-						.Add(this.Expiration, EventType.BuffTimeout, env);
-			}
-		}
-
-		protected void Dispose(bool disposing)
-		{
-			if (this.Expiration == 0)
-			{
-				return;
-			}
-
-			// Buff在垃圾回收或者主动Dispose,都需要释放Timer回调.非托管资源
-			World.Instance.GetComponent<TimerComponent>().Remove(this.TimerId);
-
-			this.expiration = 0;
-		}
-
-		~Buff()
-		{
-			this.Dispose(false);
-		}
-
-		public void Dispose()
-		{
-			this.Dispose(true);
-		}
-
-		public override void EndInit()
-		{
-			base.EndInit();
-
-			if (this.Expiration != 0)
-			{
-				// 注册Timer回调
-				Env env = new Env();
-				env[EnvKey.OwnerId] = this.OwnerId;
-				env[EnvKey.BuffId] = this.Id;
-				this.TimerId = World.Instance.GetComponent<TimerComponent>()
-						.Add(this.Expiration, EventType.BuffTimeout, env);
-			}
-		}
-
-		[BsonIgnore]
-		public BuffConfig Config
-		{
-			get
-			{
-				return World.Instance.GetComponent<ConfigComponent>().Get<BuffConfig>(this.configId);
-			}
-		}
-
-		[BsonIgnore]
-		public ObjectId OwnerId
-		{
-			get
-			{
-				return this.ownerId;
-			}
-
-			set
-			{
-				this.ownerId = value;
-			}
-		}
-	}
+using System;
+using Common.Base;
+using Common.Helper;
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Model
+{
+	public class Buff: Entity<Buff>, IDisposable
+	{
+		[BsonElement]
+		private int configId { get; set; }
+
+		[BsonElement]
+		private ObjectId ownerId;
+
+		[BsonElement]
+		private long expiration;
+
+		[BsonIgnore]
+		private ObjectId timerId;
+
+		[BsonIgnore]
+		public long Expiration
+		{
+			get
+			{
+				return this.expiration;
+			}
+			set
+			{
+				this.expiration = value;
+			}
+		}
+
+		[BsonIgnore]
+		public ObjectId TimerId
+		{
+			get
+			{
+				return this.timerId;
+			}
+			set
+			{
+				this.timerId = value;
+			}
+		}
+
+		public Buff(int configId, ObjectId ownerId)
+		{
+			this.configId = configId;
+			this.ownerId = ownerId;
+			if (this.Config.Duration != 0)
+			{
+				this.Expiration = TimeHelper.Now() + this.Config.Duration;
+			}
+
+			if (this.Expiration != 0)
+			{
+				// 注册Timer回调
+				Env env = new Env();
+				env[EnvKey.OwnerId] = this.OwnerId;
+				env[EnvKey.BuffId] = this.Id;
+				this.TimerId = World.Instance.GetComponent<TimerComponent>()
+						.Add(this.Expiration, EventType.BuffTimeout, env);
+			}
+		}
+
+		protected void Dispose(bool disposing)
+		{
+			if (this.Expiration == 0)
+			{
+				return;
+			}
+
+			// Buff在垃圾回收或者主动Dispose,都需要释放Timer回调.非托管资源
+			World.Instance.GetComponent<TimerComponent>().Remove(this.TimerId);
+
+			this.expiration = 0;
+		}
+
+		~Buff()
+		{
+			this.Dispose(false);
+		}
+
+		public void Dispose()
+		{
+			this.Dispose(true);
+		}
+
+		public override void EndInit()
+		{
+			base.EndInit();
+
+			if (this.Expiration != 0)
+			{
+				// 注册Timer回调
+				Env env = new Env();
+				env[EnvKey.OwnerId] = this.OwnerId;
+				env[EnvKey.BuffId] = this.Id;
+				this.TimerId = World.Instance.GetComponent<TimerComponent>()
+						.Add(this.Expiration, EventType.BuffTimeout, env);
+			}
+		}
+
+		[BsonIgnore]
+		public BuffConfig Config
+		{
+			get
+			{
+				return World.Instance.GetComponent<ConfigComponent>().Get<BuffConfig>(this.configId);
+			}
+		}
+
+		[BsonIgnore]
+		public ObjectId OwnerId
+		{
+			get
+			{
+				return this.ownerId;
+			}
+
+			set
+			{
+				this.ownerId = value;
+			}
+		}
+	}
 }

+ 7 - 7
CSharp/Game/Model/BuffType.cs

@@ -1,8 +1,8 @@
-namespace Model
-{
-	public enum BuffType
-	{
-		// 眩晕
-		Dizziness = 0,
-	}
+namespace Model
+{
+	public enum BuffType
+	{
+		// 眩晕
+		Dizziness = 0,
+	}
 }

+ 27 - 27
CSharp/Game/Model/Component/ActorComponent.cs

@@ -1,28 +1,28 @@
-using System.Collections.Generic;
-using Common.Base;
-using MongoDB.Bson;
-
-namespace Model
-{
-	public class ActorComponent : Component<World>
-	{
-		private readonly Dictionary<ObjectId, Actor> actors = new Dictionary<ObjectId, Actor>();
-
-		public Actor Get(ObjectId id)
-		{
-			return this.actors[id];
-		}
-
-		public void Add(Actor actor)
-		{
-			this.actors[actor.Id] = actor;
-		}
-
-		public void Remove(ObjectId id)
-		{
-			Actor actor = this.Get(id);
-			this.actors.Remove(id);
-			actor.Dispose();
-		}
-	}
+using System.Collections.Generic;
+using Common.Base;
+using MongoDB.Bson;
+
+namespace Model
+{
+	public class ActorComponent : Component<World>
+	{
+		private readonly Dictionary<ObjectId, Actor> actors = new Dictionary<ObjectId, Actor>();
+
+		public Actor Get(ObjectId id)
+		{
+			return this.actors[id];
+		}
+
+		public void Add(Actor actor)
+		{
+			this.actors[actor.Id] = actor;
+		}
+
+		public void Remove(ObjectId id)
+		{
+			Actor actor = this.Get(id);
+			this.actors.Remove(id);
+			actor.Dispose();
+		}
+	}
 }

+ 91 - 91
CSharp/Game/Model/Component/BehaviorTreeComponent.cs

@@ -1,92 +1,92 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Common.Base;
-
-namespace Model
-{
-	public class BehaviorTreeComponent : Component<World>, IAssemblyLoader, IStart
-	{
-		private Dictionary<int, BehaviorTree> behaviorTrees;
-
-		private Dictionary<NodeType, Func<NodeConfig, Node>> dictionary =
-				new Dictionary<NodeType, Func<NodeConfig, Node>>();
-
-		public void Load(Assembly assembly)
-		{
-			this.behaviorTrees = new Dictionary<int, BehaviorTree>();
-			dictionary = new Dictionary<NodeType, Func<NodeConfig, Node>>();
-			Type[] types = assembly.GetTypes();
-			foreach (Type type in types)
-			{
-				object[] attrs = type.GetCustomAttributes(typeof(NodeAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-
-				NodeAttribute attribute = attrs[0] as NodeAttribute;
-				Type classType = type;
-				if (this.dictionary.ContainsKey(attribute.Type))
-				{
-					throw new GameException($"已经存在同类节点: {attribute.Type}");
-				}
-				this.dictionary.Add(attribute.Type, config => (Node)Activator.CreateInstance(classType, config));
-			}
-		}
-
-		public void Start()
-		{
-			TreeConfig[] configs = World.Instance.GetComponent<ConfigComponent>().GetAll<TreeConfig>();
-			foreach (TreeConfig proto in configs)
-			{
-				behaviorTrees[proto.Id] = CreateTree(proto);
-			}
-		}
-
-		public BehaviorTree this[int id]
-		{
-			get
-			{
-				BehaviorTree behaviorTree;
-				if (!this.behaviorTrees.TryGetValue(id, out behaviorTree))
-				{
-					throw new GameException($"无法找到行为树: {id}");
-				}
-				return behaviorTree;
-			}
-		}
-
-		private Node CreateOneNode(NodeConfig proto)
-		{
-			NodeType nodeType = proto.Type;
-			if (!this.dictionary.ContainsKey(nodeType))
-			{
-				throw new KeyNotFoundException($"NodeType没有定义该节点: {nodeType}");
-			}
-			return this.dictionary[nodeType](proto);
-		}
-
-		private Node CreateTreeNode(NodeConfig proto)
-		{
-			Node node = this.CreateOneNode(proto);
-			if (proto.Children == null)
-			{
-				return node;
-			}
-
-			foreach (NodeConfig nodeProto in proto.Children)
-			{
-				Node childNode = this.CreateTreeNode(nodeProto);
-				node.AddChild(childNode);
-			}
-			return node;
-		}
-
-		private BehaviorTree CreateTree(TreeConfig treeConfig)
-		{
-			Node node = this.CreateTreeNode(treeConfig.Root);
-			return new BehaviorTree(node);
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using Common.Base;
+
+namespace Model
+{
+	public class BehaviorTreeComponent : Component<World>, IAssemblyLoader, IStart
+	{
+		private Dictionary<int, BehaviorTree> behaviorTrees;
+
+		private Dictionary<NodeType, Func<NodeConfig, Node>> dictionary =
+				new Dictionary<NodeType, Func<NodeConfig, Node>>();
+
+		public void Load(Assembly assembly)
+		{
+			this.behaviorTrees = new Dictionary<int, BehaviorTree>();
+			dictionary = new Dictionary<NodeType, Func<NodeConfig, Node>>();
+			Type[] types = assembly.GetTypes();
+			foreach (Type type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof(NodeAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+
+				NodeAttribute attribute = attrs[0] as NodeAttribute;
+				Type classType = type;
+				if (this.dictionary.ContainsKey(attribute.Type))
+				{
+					throw new GameException($"已经存在同类节点: {attribute.Type}");
+				}
+				this.dictionary.Add(attribute.Type, config => (Node)Activator.CreateInstance(classType, config));
+			}
+		}
+
+		public void Start()
+		{
+			TreeConfig[] configs = World.Instance.GetComponent<ConfigComponent>().GetAll<TreeConfig>();
+			foreach (TreeConfig proto in configs)
+			{
+				behaviorTrees[proto.Id] = CreateTree(proto);
+			}
+		}
+
+		public BehaviorTree this[int id]
+		{
+			get
+			{
+				BehaviorTree behaviorTree;
+				if (!this.behaviorTrees.TryGetValue(id, out behaviorTree))
+				{
+					throw new GameException($"无法找到行为树: {id}");
+				}
+				return behaviorTree;
+			}
+		}
+
+		private Node CreateOneNode(NodeConfig proto)
+		{
+			NodeType nodeType = proto.Type;
+			if (!this.dictionary.ContainsKey(nodeType))
+			{
+				throw new KeyNotFoundException($"NodeType没有定义该节点: {nodeType}");
+			}
+			return this.dictionary[nodeType](proto);
+		}
+
+		private Node CreateTreeNode(NodeConfig proto)
+		{
+			Node node = this.CreateOneNode(proto);
+			if (proto.Children == null)
+			{
+				return node;
+			}
+
+			foreach (NodeConfig nodeProto in proto.Children)
+			{
+				Node childNode = this.CreateTreeNode(nodeProto);
+				node.AddChild(childNode);
+			}
+			return node;
+		}
+
+		private BehaviorTree CreateTree(TreeConfig treeConfig)
+		{
+			Node node = this.CreateTreeNode(treeConfig.Root);
+			return new BehaviorTree(node);
+		}
+	}
 }

+ 129 - 129
CSharp/Game/Model/Component/BuffComponent.cs

@@ -1,130 +1,130 @@
-using System;
-using System.Collections.Generic;
-using Common.Base;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-#pragma warning disable 4014
-
-namespace Model
-{
-	public class BuffComponent: Component<Unit>
-	{
-		[BsonElement]
-		private HashSet<Buff> buffs;
-
-		[BsonIgnore]
-		private Dictionary<ObjectId, Buff> idBuff;
-
-		[BsonIgnore]
-		private MultiMap<BuffType, Buff> typeBuff;
-
-		public BuffComponent()
-		{
-			this.buffs = new HashSet<Buff>();
-			this.idBuff = new Dictionary<ObjectId, Buff>();
-			this.typeBuff = new MultiMap<BuffType, Buff>();
-		}
-
-		public override void BeginInit()
-		{
-			base.BeginInit();
-
-			this.buffs = new HashSet<Buff>();
-			this.idBuff = new Dictionary<ObjectId, Buff>();
-			this.typeBuff = new MultiMap<BuffType, Buff>();
-		}
-
-		public override void EndInit()
-		{
-			base.EndInit();
-
-			foreach (Buff buff in this.buffs)
-			{
-				this.idBuff.Add(buff.Id, buff);
-				this.typeBuff.Add(buff.Config.Type, buff);
-			}
-		}
-
-		public void Add(Buff buff)
-		{
-			if (this.buffs.Contains(buff))
-			{
-				throw new ArgumentException($"already exist same buff, Id: {buff.Id} ConfigId: {buff.Config.Id}");
-			}
-
-			if (this.idBuff.ContainsKey(buff.Id))
-			{
-				throw new ArgumentException($"already exist same buff, Id: {buff.Id} ConfigId: {buff.Config.Id}");
-			}
-
-			Env env = new Env();
-			env[EnvKey.Owner] = this.Owner;
-			env[EnvKey.Buff] = buff;
-
-			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.BeforeAddBuff, env);
-
-			this.buffs.Add(buff);
-			this.idBuff.Add(buff.Id, buff);
-			this.typeBuff.Add(buff.Config.Type, buff);
-
-			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.AfterAddBuff, env);
-		}
-
-		public Buff GetById(ObjectId id)
-		{
-			if (!this.idBuff.ContainsKey(id))
-			{
-				return null;
-			}
-
-			return this.idBuff[id];
-		}
-
-		public Buff GetOneByType(BuffType type)
-		{
-			return this.typeBuff.GetOne(type);
-		}
-
-		public Buff[] GetByType(BuffType type)
-		{
-			return this.typeBuff.GetAll(type);
-		}
-
-		private void Remove(Buff buff)
-		{
-			if (buff == null)
-			{
-				return;
-			}
-
-			Env env = new Env();
-			env[EnvKey.Owner] = this.Owner;
-			env[EnvKey.Buff] = buff;
-
-			World.Instance.GetComponent<EventComponent<EventAttribute>>()
-					.RunAsync(EventType.BeforeRemoveBuff, env);
-
-			this.buffs.Remove(buff);
-			this.idBuff.Remove(buff.Id);
-			this.typeBuff.Remove(buff.Config.Type, buff);
-
-			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.AfterRemoveBuff, env);
-			buff.Dispose();
-		}
-
-		public void RemoveById(ObjectId id)
-		{
-			Buff buff = this.GetById(id);
-			this.Remove(buff);
-		}
-
-		public void RemoveByType(BuffType type)
-		{
-			Buff[] allbuffs = this.GetByType(type);
-			foreach (Buff buff in allbuffs)
-			{
-				this.Remove(buff);
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+using Common.Base;
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+#pragma warning disable 4014
+
+namespace Model
+{
+	public class BuffComponent: Component<Unit>
+	{
+		[BsonElement]
+		private HashSet<Buff> buffs;
+
+		[BsonIgnore]
+		private Dictionary<ObjectId, Buff> idBuff;
+
+		[BsonIgnore]
+		private MultiMap<BuffType, Buff> typeBuff;
+
+		public BuffComponent()
+		{
+			this.buffs = new HashSet<Buff>();
+			this.idBuff = new Dictionary<ObjectId, Buff>();
+			this.typeBuff = new MultiMap<BuffType, Buff>();
+		}
+
+		public override void BeginInit()
+		{
+			base.BeginInit();
+
+			this.buffs = new HashSet<Buff>();
+			this.idBuff = new Dictionary<ObjectId, Buff>();
+			this.typeBuff = new MultiMap<BuffType, Buff>();
+		}
+
+		public override void EndInit()
+		{
+			base.EndInit();
+
+			foreach (Buff buff in this.buffs)
+			{
+				this.idBuff.Add(buff.Id, buff);
+				this.typeBuff.Add(buff.Config.Type, buff);
+			}
+		}
+
+		public void Add(Buff buff)
+		{
+			if (this.buffs.Contains(buff))
+			{
+				throw new ArgumentException($"already exist same buff, Id: {buff.Id} ConfigId: {buff.Config.Id}");
+			}
+
+			if (this.idBuff.ContainsKey(buff.Id))
+			{
+				throw new ArgumentException($"already exist same buff, Id: {buff.Id} ConfigId: {buff.Config.Id}");
+			}
+
+			Env env = new Env();
+			env[EnvKey.Owner] = this.Owner;
+			env[EnvKey.Buff] = buff;
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.BeforeAddBuff, env);
+
+			this.buffs.Add(buff);
+			this.idBuff.Add(buff.Id, buff);
+			this.typeBuff.Add(buff.Config.Type, buff);
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.AfterAddBuff, env);
+		}
+
+		public Buff GetById(ObjectId id)
+		{
+			if (!this.idBuff.ContainsKey(id))
+			{
+				return null;
+			}
+
+			return this.idBuff[id];
+		}
+
+		public Buff GetOneByType(BuffType type)
+		{
+			return this.typeBuff.GetOne(type);
+		}
+
+		public Buff[] GetByType(BuffType type)
+		{
+			return this.typeBuff.GetAll(type);
+		}
+
+		private void Remove(Buff buff)
+		{
+			if (buff == null)
+			{
+				return;
+			}
+
+			Env env = new Env();
+			env[EnvKey.Owner] = this.Owner;
+			env[EnvKey.Buff] = buff;
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>()
+					.RunAsync(EventType.BeforeRemoveBuff, env);
+
+			this.buffs.Remove(buff);
+			this.idBuff.Remove(buff.Id);
+			this.typeBuff.Remove(buff.Config.Type, buff);
+
+			World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(EventType.AfterRemoveBuff, env);
+			buff.Dispose();
+		}
+
+		public void RemoveById(ObjectId id)
+		{
+			Buff buff = this.GetById(id);
+			this.Remove(buff);
+		}
+
+		public void RemoveByType(BuffType type)
+		{
+			Buff[] allbuffs = this.GetByType(type);
+			foreach (Buff buff in allbuffs)
+			{
+				this.Remove(buff);
+			}
+		}
+	}
 }

+ 15 - 15
CSharp/Game/Model/Component/ChannelUnitInfoComponent.cs

@@ -1,16 +1,16 @@
-using Common.Base;
-using Common.Network;
-using MongoDB.Bson;
-
-namespace Model
-{
-	/// <summary>
-	/// channel中保存Unit一些信息,例如帐号
-	/// </summary>
-	public class ChannelUnitInfoComponent: Component<AChannel>
-	{
-		public byte[] Account { get; set; }
-		public ObjectId UnitId { get; set; }
-		public string ServerName { get; set; }
-	}
+using Common.Base;
+using Common.Network;
+using MongoDB.Bson;
+
+namespace Model
+{
+	/// <summary>
+	/// channel中保存Unit一些信息,例如帐号
+	/// </summary>
+	public class ChannelUnitInfoComponent: Component<AChannel>
+	{
+		public byte[] Account { get; set; }
+		public ObjectId UnitId { get; set; }
+		public string ServerName { get; set; }
+	}
 }

+ 76 - 76
CSharp/Game/Model/Component/ConfigComponent.cs

@@ -1,77 +1,77 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Common.Base;
-
-namespace Model
-{
-	public class ConfigComponent: Component<World>, IAssemblyLoader
-	{
-		private Dictionary<Type, ICategory> allConfig;
-
-		public void Load(Assembly assembly)
-		{
-			this.allConfig = new Dictionary<Type, ICategory>();
-			Type[] types = assembly.GetTypes();
-
-			ServerType serverType = World.Instance.Options.ServerType;
-
-			foreach (Type type in types)
-			{
-				object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-				ConfigAttribute configAttribute = (ConfigAttribute) attrs[0];
-				if (!configAttribute.Contains(serverType))
-				{
-					continue;
-				}
-
-				object obj = (Activator.CreateInstance(type));
-
-				ICategory iCategory = obj as ICategory;
-				if (iCategory == null)
-				{
-					throw new Exception($"class: {type.Name} not inherit from ACategory");
-				}
-				iCategory.BeginInit();
-				iCategory.EndInit();
-
-				this.allConfig[iCategory.ConfigType] = iCategory;
-			}
-		}
-
-		public T Get<T>(int id) where T : AConfig
-		{
-			Type type = typeof (T);
-			ICategory configCategory;
-			if (!this.allConfig.TryGetValue(type, out configCategory))
-			{
-				throw new KeyNotFoundException($"ConfigComponent not found key: {type.FullName}");
-			}
-			return ((ACategory<T>) configCategory)[id];
-		}
-
-		public T[] GetAll<T>() where T : AConfig
-		{
-			Type type = typeof (T);
-			ICategory configCategory;
-			if (!this.allConfig.TryGetValue(type, out configCategory))
-			{
-				throw new KeyNotFoundException($"ConfigComponent not found key: {type.FullName}");
-			}
-			return ((ACategory<T>) configCategory).GetAll();
-		}
-
-		public T GetCategory<T>() where T : class, ICategory, new()
-		{
-			T t = new T();
-			Type type = t.ConfigType;
-			ICategory category;
-			bool ret = this.allConfig.TryGetValue(type, out category);
-			return ret? (T) category : null;
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using Common.Base;
+
+namespace Model
+{
+	public class ConfigComponent: Component<World>, IAssemblyLoader
+	{
+		private Dictionary<Type, ICategory> allConfig;
+
+		public void Load(Assembly assembly)
+		{
+			this.allConfig = new Dictionary<Type, ICategory>();
+			Type[] types = assembly.GetTypes();
+
+			ServerType serverType = World.Instance.Options.ServerType;
+
+			foreach (Type type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+				ConfigAttribute configAttribute = (ConfigAttribute) attrs[0];
+				if (!configAttribute.Contains(serverType))
+				{
+					continue;
+				}
+
+				object obj = (Activator.CreateInstance(type));
+
+				ICategory iCategory = obj as ICategory;
+				if (iCategory == null)
+				{
+					throw new Exception($"class: {type.Name} not inherit from ACategory");
+				}
+				iCategory.BeginInit();
+				iCategory.EndInit();
+
+				this.allConfig[iCategory.ConfigType] = iCategory;
+			}
+		}
+
+		public T Get<T>(int id) where T : AConfig
+		{
+			Type type = typeof (T);
+			ICategory configCategory;
+			if (!this.allConfig.TryGetValue(type, out configCategory))
+			{
+				throw new KeyNotFoundException($"ConfigComponent not found key: {type.FullName}");
+			}
+			return ((ACategory<T>) configCategory)[id];
+		}
+
+		public T[] GetAll<T>() where T : AConfig
+		{
+			Type type = typeof (T);
+			ICategory configCategory;
+			if (!this.allConfig.TryGetValue(type, out configCategory))
+			{
+				throw new KeyNotFoundException($"ConfigComponent not found key: {type.FullName}");
+			}
+			return ((ACategory<T>) configCategory).GetAll();
+		}
+
+		public T GetCategory<T>() where T : class, ICategory, new()
+		{
+			T t = new T();
+			Type type = t.ConfigType;
+			ICategory category;
+			bool ret = this.allConfig.TryGetValue(type, out category);
+			return ret? (T) category : null;
+		}
+	}
 }

+ 211 - 211
CSharp/Game/Model/Component/EventComponent.cs

@@ -1,212 +1,212 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading.Tasks;
-using Common.Base;
-using Common.Logger;
-
-namespace Model
-{
-	public class EventComponent<AttributeType>: Component<World>, IAssemblyLoader
-			where AttributeType : AEventAttribute
-	{
-		private Dictionary<EventType, List<object>> allEvents;
-
-		public void Load(Assembly assembly)
-		{
-			this.allEvents = new Dictionary<EventType, List<object>>();
-
-			ServerType serverType = World.Instance.Options.ServerType;
-
-			Type[] types = assembly.GetTypes();
-			foreach (Type t in types)
-			{
-				object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-
-				AEventAttribute aEventAttribute = (AEventAttribute) attrs[0];
-				if (!aEventAttribute.Contains(serverType))
-				{
-					continue;
-				}
-
-				object obj = Activator.CreateInstance(t);
-				if (obj == null)
-				{
-					throw new Exception($"event not inherit IEvent or IEventAsync interface: {obj.GetType().FullName}");
-				}
-				if (!this.allEvents.ContainsKey(aEventAttribute.Type))
-				{
-					this.allEvents.Add(aEventAttribute.Type, new List<object>());
-				}
-				this.allEvents[aEventAttribute.Type].Add(obj);
-			}
-		}
-
-		public async Task RunAsync(EventType type)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent iEvent = obj as AEvent;
-					if (iEvent == null)
-					{
-						throw new GameException($"event type: {type} is not IEvent");
-					}
-					iEvent.Run();
-					await iEvent.RunAsync();
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-
-		public async Task RunAsync<A>(EventType type, A a)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent<A> iEvent = obj as AEvent<A>;
-					if (iEvent == null)
-					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}>");
-					}
-					iEvent.Run(a);
-					await iEvent.RunAsync(a);
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-
-		public async Task RunAsync<A, B>(EventType type, A a, B b)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent<A, B> iEvent = obj as AEvent<A, B>;
-					if (iEvent == null)
-					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}>");
-					}
-					iEvent.Run(a, b);
-					await iEvent.RunAsync(a, b);
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-
-		public async Task RunAsync<A, B, C>(EventType type, A a, B b, C c)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent<A, B, C> iEvent = obj as AEvent<A, B, C>;
-					if (iEvent == null)
-					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}>");
-					}
-					iEvent.Run(a, b, c);
-					await iEvent.RunAsync(a, b, c);
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-
-		public async Task RunAsync<A, B, C, D>(EventType type, A a, B b, C c, D d)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent<A, B, C, D> iEvent = obj as AEvent<A, B, C, D>;
-					if (iEvent == null)
-					{
-						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}>");
-					}
-					iEvent.Run(a, b, c, d);
-					await iEvent.RunAsync(a, b, c, d);
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-
-		public async Task RunAsync<A, B, C, D, E>(EventType type, A a, B b, C c, D d, E e)
-		{
-			List<object> iEvents = null;
-			if (!this.allEvents.TryGetValue(type, out iEvents))
-			{
-				return;
-			}
-
-			foreach (object obj in iEvents)
-			{
-				try
-				{
-					AEvent<A, B, C, D, E> iEvent = obj as AEvent<A, B, C, D, E>;
-					if (iEvent == null)
-					{
-						throw new GameException(
-								$"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}, {typeof (E).Name}>");
-					}
-					iEvent.Run(a, b, c, d, e);
-					await iEvent.RunAsync(a, b, c, d, e);
-				}
-				catch (Exception err)
-				{
-					Log.Debug(err.ToString());
-				}
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading.Tasks;
+using Common.Base;
+using Common.Logger;
+
+namespace Model
+{
+	public class EventComponent<AttributeType>: Component<World>, IAssemblyLoader
+			where AttributeType : AEventAttribute
+	{
+		private Dictionary<EventType, List<object>> allEvents;
+
+		public void Load(Assembly assembly)
+		{
+			this.allEvents = new Dictionary<EventType, List<object>>();
+
+			ServerType serverType = World.Instance.Options.ServerType;
+
+			Type[] types = assembly.GetTypes();
+			foreach (Type t in types)
+			{
+				object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+
+				AEventAttribute aEventAttribute = (AEventAttribute) attrs[0];
+				if (!aEventAttribute.Contains(serverType))
+				{
+					continue;
+				}
+
+				object obj = Activator.CreateInstance(t);
+				if (obj == null)
+				{
+					throw new Exception($"event not inherit IEvent or IEventAsync interface: {obj.GetType().FullName}");
+				}
+				if (!this.allEvents.ContainsKey(aEventAttribute.Type))
+				{
+					this.allEvents.Add(aEventAttribute.Type, new List<object>());
+				}
+				this.allEvents[aEventAttribute.Type].Add(obj);
+			}
+		}
+
+		public async Task RunAsync(EventType type)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent iEvent = obj as AEvent;
+					if (iEvent == null)
+					{
+						throw new GameException($"event type: {type} is not IEvent");
+					}
+					iEvent.Run();
+					await iEvent.RunAsync();
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+
+		public async Task RunAsync<A>(EventType type, A a)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent<A> iEvent = obj as AEvent<A>;
+					if (iEvent == null)
+					{
+						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}>");
+					}
+					iEvent.Run(a);
+					await iEvent.RunAsync(a);
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+
+		public async Task RunAsync<A, B>(EventType type, A a, B b)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent<A, B> iEvent = obj as AEvent<A, B>;
+					if (iEvent == null)
+					{
+						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}>");
+					}
+					iEvent.Run(a, b);
+					await iEvent.RunAsync(a, b);
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+
+		public async Task RunAsync<A, B, C>(EventType type, A a, B b, C c)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent<A, B, C> iEvent = obj as AEvent<A, B, C>;
+					if (iEvent == null)
+					{
+						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}>");
+					}
+					iEvent.Run(a, b, c);
+					await iEvent.RunAsync(a, b, c);
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+
+		public async Task RunAsync<A, B, C, D>(EventType type, A a, B b, C c, D d)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent<A, B, C, D> iEvent = obj as AEvent<A, B, C, D>;
+					if (iEvent == null)
+					{
+						throw new GameException($"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}>");
+					}
+					iEvent.Run(a, b, c, d);
+					await iEvent.RunAsync(a, b, c, d);
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+
+		public async Task RunAsync<A, B, C, D, E>(EventType type, A a, B b, C c, D d, E e)
+		{
+			List<object> iEvents = null;
+			if (!this.allEvents.TryGetValue(type, out iEvents))
+			{
+				return;
+			}
+
+			foreach (object obj in iEvents)
+			{
+				try
+				{
+					AEvent<A, B, C, D, E> iEvent = obj as AEvent<A, B, C, D, E>;
+					if (iEvent == null)
+					{
+						throw new GameException(
+								$"event type: {type} is not IEvent<{typeof (A).Name}, {typeof (B).Name}, {typeof (C).Name}, {typeof (D).Name}, {typeof (E).Name}>");
+					}
+					iEvent.Run(a, b, c, d, e);
+					await iEvent.RunAsync(a, b, c, d, e);
+				}
+				catch (Exception err)
+				{
+					Log.Debug(err.ToString());
+				}
+			}
+		}
+	}
 }

+ 46 - 46
CSharp/Game/Model/Component/FactoryComponent.cs

@@ -1,47 +1,47 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using Common.Base;
-
-namespace Model
-{
-	public class FactoryComponent<T>: Component<World>, IAssemblyLoader where T : Entity<T>
-	{
-		private Dictionary<int, IFactory<T>> allConfig;
-
-		public void Load(Assembly assembly)
-		{
-			this.allConfig = new Dictionary<int, IFactory<T>>();
-			Type[] types = assembly.GetTypes();
-			foreach (Type type in types)
-			{
-				object[] attrs = type.GetCustomAttributes(typeof (FactoryAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-
-				FactoryAttribute attribute = (FactoryAttribute) attrs[0];
-				if (attribute.ClassType != typeof (T))
-				{
-					continue;
-				}
-
-				object obj = (Activator.CreateInstance(type));
-
-				var iFactory = obj as IFactory<T>;
-				if (iFactory == null)
-				{
-					throw new Exception($"class: {type.Name} not inherit from IFactory");
-				}
-
-				this.allConfig[attribute.Type] = iFactory;
-			}
-		}
-
-		public T Create(int type, int configId)
-		{
-			return this.allConfig[type].Create(configId);
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using Common.Base;
+
+namespace Model
+{
+	public class FactoryComponent<T>: Component<World>, IAssemblyLoader where T : Entity<T>
+	{
+		private Dictionary<int, IFactory<T>> allConfig;
+
+		public void Load(Assembly assembly)
+		{
+			this.allConfig = new Dictionary<int, IFactory<T>>();
+			Type[] types = assembly.GetTypes();
+			foreach (Type type in types)
+			{
+				object[] attrs = type.GetCustomAttributes(typeof (FactoryAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+
+				FactoryAttribute attribute = (FactoryAttribute) attrs[0];
+				if (attribute.ClassType != typeof (T))
+				{
+					continue;
+				}
+
+				object obj = (Activator.CreateInstance(type));
+
+				var iFactory = obj as IFactory<T>;
+				if (iFactory == null)
+				{
+					throw new Exception($"class: {type.Name} not inherit from IFactory");
+				}
+
+				this.allConfig[attribute.Type] = iFactory;
+			}
+		}
+
+		public T Create(int type, int configId)
+		{
+			return this.allConfig[type].Create(configId);
+		}
+	}
 }

+ 110 - 110
CSharp/Game/Model/Component/GateNetworkComponent.cs

@@ -1,111 +1,111 @@
-using System;
-using System.Collections.Generic;
-using Common.Base;
-using Common.Network;
-using MongoDB.Bson;
-using TNet;
-using UNet;
-
-namespace Model
-{
-	/// <summary>
-	/// gate对外连接使用
-	/// </summary>
-	public class GateNetworkComponent: Component<World>, IUpdate, IStart
-	{
-		private IService service;
-
-		private readonly Dictionary<ObjectId, AChannel> unitIdChannels =
-				new Dictionary<ObjectId, AChannel>();
-
-		private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
-		{
-			switch (protocol)
-			{
-				case NetworkProtocol.TCP:
-					this.service = new TService(host, port);
-					break;
-				case NetworkProtocol.UDP:
-					this.service = new UService(host, port);
-					break;
-				default:
-					throw new ArgumentOutOfRangeException("protocol");
-			}
-
-			this.AcceptChannel();
-		}
-
-		public void Start()
-		{
-			this.Accept(World.Instance.Options.GateHost, World.Instance.Options.GatePort,
-					World.Instance.Options.Protocol);
-		}
-
-		public void Update()
-		{
-			this.service.Update();
-		}
-
-		/// <summary>
-		/// 接收连接
-		/// </summary>
-		private async void AcceptChannel()
-		{
-			while (true)
-			{
-				AChannel channel = await this.service.GetChannel();
-				channel.OnDispose += this.OnChannelDispose;
-				ProcessChannel(channel);
-			}
-		}
-
-		/// <summary>
-		/// 接收分发封包
-		/// </summary>
-		/// <param name="channel"></param>
-		private static async void ProcessChannel(AChannel channel)
-		{
-			while (true)
-			{
-				byte[] messageBytes = await channel.RecvAsync();
-				Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
-				if (!OpcodeHelper.IsClientMessage(opcode))
-				{
-					continue;
-				}
-
-				ObjectId unitId = channel.GetComponent<ChannelUnitInfoComponent>().UnitId;
-				Actor actor = World.Instance.GetComponent<ActorComponent>().Get(unitId);
-				actor.Add(messageBytes);
-			}
-		}
-
-		// channel删除的时候需要清除与unit id的关联
-		private void OnChannelDispose(AChannel channel)
-		{
-			ChannelUnitInfoComponent channelUnitInfoComponent =
-					channel.GetComponent<ChannelUnitInfoComponent>();
-			if (channelUnitInfoComponent != null)
-			{
-				this.unitIdChannels.Remove(channelUnitInfoComponent.UnitId);
-			}
-		}
-
-		// 将unit id与channel关联起来
-		public void AssociateUnitIdAndChannel(ObjectId id, AChannel channel)
-		{
-			this.unitIdChannels[id] = channel;
-		}
-
-		public void SendAsync(ObjectId id, byte[] buffer)
-		{
-			AChannel channel;
-			if (!this.unitIdChannels.TryGetValue(id, out channel))
-			{
-				return;
-			}
-
-			channel.SendAsync(buffer);
-		}
-	}
+using System;
+using System.Collections.Generic;
+using Common.Base;
+using Common.Network;
+using MongoDB.Bson;
+using TNet;
+using UNet;
+
+namespace Model
+{
+	/// <summary>
+	/// gate对外连接使用
+	/// </summary>
+	public class GateNetworkComponent: Component<World>, IUpdate, IStart
+	{
+		private IService service;
+
+		private readonly Dictionary<ObjectId, AChannel> unitIdChannels =
+				new Dictionary<ObjectId, AChannel>();
+
+		private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
+		{
+			switch (protocol)
+			{
+				case NetworkProtocol.TCP:
+					this.service = new TService(host, port);
+					break;
+				case NetworkProtocol.UDP:
+					this.service = new UService(host, port);
+					break;
+				default:
+					throw new ArgumentOutOfRangeException("protocol");
+			}
+
+			this.AcceptChannel();
+		}
+
+		public void Start()
+		{
+			this.Accept(World.Instance.Options.GateHost, World.Instance.Options.GatePort,
+					World.Instance.Options.Protocol);
+		}
+
+		public void Update()
+		{
+			this.service.Update();
+		}
+
+		/// <summary>
+		/// 接收连接
+		/// </summary>
+		private async void AcceptChannel()
+		{
+			while (true)
+			{
+				AChannel channel = await this.service.GetChannel();
+				channel.OnDispose += this.OnChannelDispose;
+				ProcessChannel(channel);
+			}
+		}
+
+		/// <summary>
+		/// 接收分发封包
+		/// </summary>
+		/// <param name="channel"></param>
+		private static async void ProcessChannel(AChannel channel)
+		{
+			while (true)
+			{
+				byte[] messageBytes = await channel.RecvAsync();
+				Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
+				if (!OpcodeHelper.IsClientMessage(opcode))
+				{
+					continue;
+				}
+
+				ObjectId unitId = channel.GetComponent<ChannelUnitInfoComponent>().UnitId;
+				Actor actor = World.Instance.GetComponent<ActorComponent>().Get(unitId);
+				actor.Add(messageBytes);
+			}
+		}
+
+		// channel删除的时候需要清除与unit id的关联
+		private void OnChannelDispose(AChannel channel)
+		{
+			ChannelUnitInfoComponent channelUnitInfoComponent =
+					channel.GetComponent<ChannelUnitInfoComponent>();
+			if (channelUnitInfoComponent != null)
+			{
+				this.unitIdChannels.Remove(channelUnitInfoComponent.UnitId);
+			}
+		}
+
+		// 将unit id与channel关联起来
+		public void AssociateUnitIdAndChannel(ObjectId id, AChannel channel)
+		{
+			this.unitIdChannels[id] = channel;
+		}
+
+		public void SendAsync(ObjectId id, byte[] buffer)
+		{
+			AChannel channel;
+			if (!this.unitIdChannels.TryGetValue(id, out channel))
+			{
+				return;
+			}
+
+			channel.SendAsync(buffer);
+		}
+	}
 }

+ 72 - 72
CSharp/Game/Model/Component/MessageComponent.cs

@@ -1,73 +1,73 @@
-using System;
-using System.Collections.Generic;
-using System.Reflection;
-using System.Threading.Tasks;
-using Common.Base;
-using Common.Helper;
-
-namespace Model
-{
-	public class MessageComponent: Component<World>, IAssemblyLoader
-	{
-		private Dictionary<Opcode, Func<byte[], byte[]>> events;
-		private Dictionary<Opcode, Func<byte[], Task<byte[]>>> eventsAsync;
-
-		public void Load(Assembly assembly)
-		{
-			this.events = new Dictionary<Opcode, Func<byte[], byte[]>>();
-			this.eventsAsync = new Dictionary<Opcode, Func<byte[], Task<byte[]>>>();
-
-			ServerType serverType = World.Instance.Options.ServerType;
-
-			Type[] types = assembly.GetTypes();
-			foreach (Type t in types)
-			{
-				object[] attrs = t.GetCustomAttributes(typeof (MessageAttribute), false);
-				if (attrs.Length == 0)
-				{
-					continue;
-				}
-
-				MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
-				if (!messageAttribute.Contains(serverType))
-				{
-					continue;
-				}
-				
-				object obj = Activator.CreateInstance(t);
-
-				IRegister iRegister = obj as IRegister;
-				iRegister?.Register();
-
-				throw new Exception($"message handler not inherit IRegister interface: {obj.GetType().FullName}");
-			}
-		}
-
-		public void Register<T, R>(Func<T, R> func)
-		{
-			Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
-			events.Add(opcode, messageBytes =>
-			{
-				T t = MongoHelper.FromBson<T>(messageBytes, 6);
-				R k = func(t);
-				return MongoHelper.ToBson(k);
-			});
-		}
-
-		public async Task<byte[]> RunAsync(Opcode opcode, byte[] messageBytes)
-		{
-			Func<byte[], byte[]> func = null;
-			if (this.events.TryGetValue(opcode, out func))
-			{
-				return func(messageBytes);
-			}
-
-			Func<byte[], Task<byte[]>> funcAsync = null;
-			if (this.eventsAsync.TryGetValue(opcode, out funcAsync))
-			{
-				return await funcAsync(messageBytes);
-			}
-			throw new GameException($"not found opcode handler: {opcode}");
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Threading.Tasks;
+using Common.Base;
+using Common.Helper;
+
+namespace Model
+{
+	public class MessageComponent: Component<World>, IAssemblyLoader
+	{
+		private Dictionary<Opcode, Func<byte[], byte[]>> events;
+		private Dictionary<Opcode, Func<byte[], Task<byte[]>>> eventsAsync;
+
+		public void Load(Assembly assembly)
+		{
+			this.events = new Dictionary<Opcode, Func<byte[], byte[]>>();
+			this.eventsAsync = new Dictionary<Opcode, Func<byte[], Task<byte[]>>>();
+
+			ServerType serverType = World.Instance.Options.ServerType;
+
+			Type[] types = assembly.GetTypes();
+			foreach (Type t in types)
+			{
+				object[] attrs = t.GetCustomAttributes(typeof (MessageAttribute), false);
+				if (attrs.Length == 0)
+				{
+					continue;
+				}
+
+				MessageAttribute messageAttribute = (MessageAttribute)attrs[0];
+				if (!messageAttribute.Contains(serverType))
+				{
+					continue;
+				}
+				
+				object obj = Activator.CreateInstance(t);
+
+				IRegister iRegister = obj as IRegister;
+				iRegister?.Register();
+
+				throw new Exception($"message handler not inherit IRegister interface: {obj.GetType().FullName}");
+			}
+		}
+
+		public void Register<T, R>(Func<T, R> func)
+		{
+			Opcode opcode = EnumHelper.FromString<Opcode>(typeof (T).Name);
+			events.Add(opcode, messageBytes =>
+			{
+				T t = MongoHelper.FromBson<T>(messageBytes, 6);
+				R k = func(t);
+				return MongoHelper.ToBson(k);
+			});
+		}
+
+		public async Task<byte[]> RunAsync(Opcode opcode, byte[] messageBytes)
+		{
+			Func<byte[], byte[]> func = null;
+			if (this.events.TryGetValue(opcode, out func))
+			{
+				return func(messageBytes);
+			}
+
+			Func<byte[], Task<byte[]>> funcAsync = null;
+			if (this.eventsAsync.TryGetValue(opcode, out funcAsync))
+			{
+				return await funcAsync(messageBytes);
+			}
+			throw new GameException($"not found opcode handler: {opcode}");
+		}
+	}
 }

+ 207 - 207
CSharp/Game/Model/Component/NetworkComponent.cs

@@ -1,208 +1,208 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Runtime.Serialization;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Threading.Tasks;
-using Common.Base;
-using Common.Helper;
-using Common.Network;
-using MongoDB.Bson;
-using TNet;
-using UNet;
-
-namespace Model
-{
-	public enum RpcResponseStatus
-	{
-		Succee,
-		Timeout,
-		Exception,
-	}
-
-	public class RpcExcetionInfo
-	{
-		public int ErrorCode { get; private set; }
-		public string ErrorInfo { get; private set; }
-
-		public RpcExcetionInfo(int errorCode, string errorInfo)
-		{
-			this.ErrorCode = errorCode;
-			this.ErrorInfo = errorInfo;
-		}
-	}
-
-	public class NetworkComponent: Component<World>, IUpdate, IStart
-	{
-		private IService service;
-
-		private int requestId;
-
-		private readonly Dictionary<int, Action<byte[], RpcResponseStatus>> requestCallback =
-				new Dictionary<int, Action<byte[], RpcResponseStatus>>();
-
-		private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
-		{
-			switch (protocol)
-			{
-				case NetworkProtocol.TCP:
-					this.service = new TService(host, port);
-					break;
-				case NetworkProtocol.UDP:
-					this.service = new UService(host, port);
-					break;
-				default:
-					throw new ArgumentOutOfRangeException("protocol");
-			}
-
-			this.AcceptChannel();
-		}
-
-		public void Start()
-		{
-			this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
-					World.Instance.Options.Protocol);
-		}
-
-		public void Update()
-		{
-			this.service.Update();
-		}
-
-		/// <summary>
-		/// 接收连接
-		/// </summary>
-		private async void AcceptChannel()
-		{
-			while (true)
-			{
-				AChannel channel = await this.service.GetChannel();
-				this.ProcessChannel(channel);
-			}
-		}
-
-		/// <summary>
-		/// 接收分发封包
-		/// </summary>
-		/// <param name="channel"></param>
-		private async void ProcessChannel(AChannel channel)
-		{
-			while (true)
-			{
-				byte[] messageBytes = await channel.RecvAsync();
-				Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
-
-				// rpc异常
-				if (opcode == Opcode.RpcException)
-				{
-					int id = BitConverter.ToInt32(messageBytes, 2);
-					this.RpcCallback(channel, id, messageBytes, RpcResponseStatus.Exception);
-					continue;
-				}
-
-				// 表示消息是rpc响应消息
-				if (opcode == Opcode.RpcResponse)
-				{
-					int id = BitConverter.ToInt32(messageBytes, 2);
-					this.RpcCallback(channel, id, messageBytes, RpcResponseStatus.Succee);
-					continue;
-				}
-
-				// 如果是server message(发给client的消息),说明这是gate server,需要根据unitid查到channel,进行发送
-				if (OpcodeHelper.IsServerMessage(opcode))
-				{
-					byte[] idBuffer = new byte[12];
-					Array.Copy(messageBytes, 2, idBuffer, 0, 12);
-					ObjectId unitId = new ObjectId(idBuffer);
-					byte[] buffer = new byte[messageBytes.Length - 6];
-					Array.Copy(messageBytes, 6, buffer, 0, buffer.Length);
-					World.Instance.GetComponent<GateNetworkComponent>().SendAsync(unitId, buffer);
-					continue;
-				}
-
-				// 处理Rpc请求,并且返回结果
-				RpcDo(channel, opcode, messageBytes);
-			}
-		}
-
-		private async static void RpcDo(AChannel channel, Opcode opcode, byte[] messageBytes)
-		{
-			byte[] opcodeBuffer;
-			int id = BitConverter.ToInt32(messageBytes, 2);
-			byte[] idBuffer = BitConverter.GetBytes(id);
-			try
-			{
-				opcodeBuffer = BitConverter.GetBytes((ushort)Opcode.RpcResponse);
-				byte[] result = await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, messageBytes);
-				channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, result });
-			}
-			catch (Exception e)
-			{
-				opcodeBuffer = BitConverter.GetBytes((ushort)Opcode.RpcException);
-				BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
-				using (MemoryStream stream = new MemoryStream())
-				{
-					formatter.Serialize(stream, e);
-					channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, stream.ToArray() });
-				}
-			}
-		}
-
-		// 消息回调或者超时回调
-		public void RpcCallback(AChannel channel, int id, byte[] buffer, RpcResponseStatus responseStatus)
-		{
-			Action<byte[], RpcResponseStatus> action;
-			if (!this.requestCallback.TryGetValue(id, out action))
-			{
-				return;
-			}
-			this.requestCallback.Remove(id);
-			action(buffer, responseStatus);
-		}
-
-		/// <summary>
-		/// Rpc请求
-		/// </summary>
-		public Task<T> RpcCall<T, K>(string address, K request, int waitTime = 0)
-		{
-			AChannel channel = this.service.GetChannel(address);
-
-			++this.requestId;
-			byte[] requestBuffer = MongoHelper.ToBson(request);
-			Opcode opcode = EnumHelper.FromString<Opcode>(request.GetType().Name);
-			byte[] opcodeBuffer = BitConverter.GetBytes((ushort)opcode);
-			byte[] idBuffer = BitConverter.GetBytes(this.requestId);
-			channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, requestBuffer });
-			var tcs = new TaskCompletionSource<T>();
-			this.requestCallback[this.requestId] = (messageBytes, status) =>
-			{
-				switch (status)
-				{
-					case RpcResponseStatus.Timeout:
-						tcs.SetException(new Exception($"rpc timeout {opcode} {MongoHelper.ToJson(request)}"));
-						return;
-					case RpcResponseStatus.Exception:
-						BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
-						Exception exception;
-						using (MemoryStream stream = new MemoryStream(messageBytes, 6, messageBytes.Length - 6))
-						{
-							exception = (Exception)formatter.Deserialize(stream);
-						}
-						tcs.SetException(exception);
-						return;
-				}
-
-				// RpcResponseStatus.Succee
-				T response = MongoHelper.FromBson<T>(messageBytes, 6);
-				tcs.SetResult(response);
-			};
-
-			if (waitTime > 0)
-			{
-				this.service.Timer.Add(TimeHelper.Now() + waitTime,
-						() => { this.RpcCallback(channel, this.requestId, null, RpcResponseStatus.Timeout); });
-			}
-			return tcs.Task;
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
+using System.Threading.Tasks;
+using Common.Base;
+using Common.Helper;
+using Common.Network;
+using MongoDB.Bson;
+using TNet;
+using UNet;
+
+namespace Model
+{
+	public enum RpcResponseStatus
+	{
+		Succee,
+		Timeout,
+		Exception,
+	}
+
+	public class RpcExcetionInfo
+	{
+		public int ErrorCode { get; private set; }
+		public string ErrorInfo { get; private set; }
+
+		public RpcExcetionInfo(int errorCode, string errorInfo)
+		{
+			this.ErrorCode = errorCode;
+			this.ErrorInfo = errorInfo;
+		}
+	}
+
+	public class NetworkComponent: Component<World>, IUpdate, IStart
+	{
+		private IService service;
+
+		private int requestId;
+
+		private readonly Dictionary<int, Action<byte[], RpcResponseStatus>> requestCallback =
+				new Dictionary<int, Action<byte[], RpcResponseStatus>>();
+
+		private void Accept(string host, int port, NetworkProtocol protocol = NetworkProtocol.TCP)
+		{
+			switch (protocol)
+			{
+				case NetworkProtocol.TCP:
+					this.service = new TService(host, port);
+					break;
+				case NetworkProtocol.UDP:
+					this.service = new UService(host, port);
+					break;
+				default:
+					throw new ArgumentOutOfRangeException("protocol");
+			}
+
+			this.AcceptChannel();
+		}
+
+		public void Start()
+		{
+			this.Accept(World.Instance.Options.Host, World.Instance.Options.Port,
+					World.Instance.Options.Protocol);
+		}
+
+		public void Update()
+		{
+			this.service.Update();
+		}
+
+		/// <summary>
+		/// 接收连接
+		/// </summary>
+		private async void AcceptChannel()
+		{
+			while (true)
+			{
+				AChannel channel = await this.service.GetChannel();
+				this.ProcessChannel(channel);
+			}
+		}
+
+		/// <summary>
+		/// 接收分发封包
+		/// </summary>
+		/// <param name="channel"></param>
+		private async void ProcessChannel(AChannel channel)
+		{
+			while (true)
+			{
+				byte[] messageBytes = await channel.RecvAsync();
+				Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
+
+				// rpc异常
+				if (opcode == Opcode.RpcException)
+				{
+					int id = BitConverter.ToInt32(messageBytes, 2);
+					this.RpcCallback(channel, id, messageBytes, RpcResponseStatus.Exception);
+					continue;
+				}
+
+				// 表示消息是rpc响应消息
+				if (opcode == Opcode.RpcResponse)
+				{
+					int id = BitConverter.ToInt32(messageBytes, 2);
+					this.RpcCallback(channel, id, messageBytes, RpcResponseStatus.Succee);
+					continue;
+				}
+
+				// 如果是server message(发给client的消息),说明这是gate server,需要根据unitid查到channel,进行发送
+				if (OpcodeHelper.IsServerMessage(opcode))
+				{
+					byte[] idBuffer = new byte[12];
+					Array.Copy(messageBytes, 2, idBuffer, 0, 12);
+					ObjectId unitId = new ObjectId(idBuffer);
+					byte[] buffer = new byte[messageBytes.Length - 6];
+					Array.Copy(messageBytes, 6, buffer, 0, buffer.Length);
+					World.Instance.GetComponent<GateNetworkComponent>().SendAsync(unitId, buffer);
+					continue;
+				}
+
+				// 处理Rpc请求,并且返回结果
+				RpcDo(channel, opcode, messageBytes);
+			}
+		}
+
+		private async static void RpcDo(AChannel channel, Opcode opcode, byte[] messageBytes)
+		{
+			byte[] opcodeBuffer;
+			int id = BitConverter.ToInt32(messageBytes, 2);
+			byte[] idBuffer = BitConverter.GetBytes(id);
+			try
+			{
+				opcodeBuffer = BitConverter.GetBytes((ushort)Opcode.RpcResponse);
+				byte[] result = await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, messageBytes);
+				channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, result });
+			}
+			catch (Exception e)
+			{
+				opcodeBuffer = BitConverter.GetBytes((ushort)Opcode.RpcException);
+				BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
+				using (MemoryStream stream = new MemoryStream())
+				{
+					formatter.Serialize(stream, e);
+					channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, stream.ToArray() });
+				}
+			}
+		}
+
+		// 消息回调或者超时回调
+		public void RpcCallback(AChannel channel, int id, byte[] buffer, RpcResponseStatus responseStatus)
+		{
+			Action<byte[], RpcResponseStatus> action;
+			if (!this.requestCallback.TryGetValue(id, out action))
+			{
+				return;
+			}
+			this.requestCallback.Remove(id);
+			action(buffer, responseStatus);
+		}
+
+		/// <summary>
+		/// Rpc请求
+		/// </summary>
+		public Task<T> RpcCall<T, K>(string address, K request, int waitTime = 0)
+		{
+			AChannel channel = this.service.GetChannel(address);
+
+			++this.requestId;
+			byte[] requestBuffer = MongoHelper.ToBson(request);
+			Opcode opcode = EnumHelper.FromString<Opcode>(request.GetType().Name);
+			byte[] opcodeBuffer = BitConverter.GetBytes((ushort)opcode);
+			byte[] idBuffer = BitConverter.GetBytes(this.requestId);
+			channel.SendAsync(new List<byte[]> { opcodeBuffer, idBuffer, requestBuffer });
+			var tcs = new TaskCompletionSource<T>();
+			this.requestCallback[this.requestId] = (messageBytes, status) =>
+			{
+				switch (status)
+				{
+					case RpcResponseStatus.Timeout:
+						tcs.SetException(new Exception($"rpc timeout {opcode} {MongoHelper.ToJson(request)}"));
+						return;
+					case RpcResponseStatus.Exception:
+						BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.All));
+						Exception exception;
+						using (MemoryStream stream = new MemoryStream(messageBytes, 6, messageBytes.Length - 6))
+						{
+							exception = (Exception)formatter.Deserialize(stream);
+						}
+						tcs.SetException(exception);
+						return;
+				}
+
+				// RpcResponseStatus.Succee
+				T response = MongoHelper.FromBson<T>(messageBytes, 6);
+				tcs.SetResult(response);
+			};
+
+			if (waitTime > 0)
+			{
+				this.service.Timer.Add(TimeHelper.Now() + waitTime,
+						() => { this.RpcCallback(channel, this.requestId, null, RpcResponseStatus.Timeout); });
+			}
+			return tcs.Task;
+		}
+	}
 }

+ 88 - 88
CSharp/Game/Model/Component/TimerComponent.cs

@@ -1,89 +1,89 @@
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Common.Base;
-using Common.Helper;
-using MongoDB.Bson;
-
-namespace Model
-{
-	public class TimerComponent: Component<World>, IUpdate
-	{
-		private class Timer
-		{
-			public ObjectId Id { get; set; }
-			public long Time { get; set; }
-			public EventType CallbackEvent { get; set; }
-			public Env Env { get; set; }
-		}
-
-		private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
-
-		/// <summary>
-		/// key: time, value: timer id
-		/// </summary>
-		private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
-		
-		public ObjectId Add(long time, EventType callbackEvent, Env env)
-		{
-			Timer timer = new Timer
-			{
-				Id = ObjectId.GenerateNewId(),
-				Time = time,
-				CallbackEvent = callbackEvent,
-				Env = env
-			};
-			this.timers[timer.Id] = timer;
-			this.timeId.Add(timer.Time, timer.Id);
-			return timer.Id;
-		}
-
-		public void Remove(ObjectId id)
-		{
-			Timer timer;
-			if (!this.timers.TryGetValue(id, out timer))
-			{
-				return;
-			}
-			this.timeId.Remove(timer.Time, timer.Id);
-		}
-
-		public Task<bool> Sleep(int time)
-		{
-			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
-			Env env = new Env();
-			env[EnvKey.SleepTimeout_TaskCompletionSource] = tcs;
-			this.Add(TimeHelper.Now() + time, EventType.SleepTimeout, env);
-			return tcs.Task;
-		}
-
-		public void Update()
-		{
-			long timeNow = TimeHelper.Now();
-
-			while (true)
-			{
-				KeyValuePair<long, List<ObjectId>> first = this.timeId.First;
-				if (first.Key > timeNow)
-				{
-					return;
-				}
-
-				List<ObjectId> timeoutId = first.Value;
-				this.timeId.Remove(first.Key);
-				foreach (ObjectId id in timeoutId)
-				{
-					Timer timer;
-					if (!this.timers.TryGetValue(id, out timer))
-					{
-						continue;
-					}
-					this.timers.Remove(id);
-#pragma warning disable 4014
-					World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(timer.CallbackEvent, timer.Env);
-#pragma warning restore 4014
-				}
-			}
-		}
-	}
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Common.Base;
+using Common.Helper;
+using MongoDB.Bson;
+
+namespace Model
+{
+	public class TimerComponent: Component<World>, IUpdate
+	{
+		private class Timer
+		{
+			public ObjectId Id { get; set; }
+			public long Time { get; set; }
+			public EventType CallbackEvent { get; set; }
+			public Env Env { get; set; }
+		}
+
+		private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
+
+		/// <summary>
+		/// key: time, value: timer id
+		/// </summary>
+		private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
+		
+		public ObjectId Add(long time, EventType callbackEvent, Env env)
+		{
+			Timer timer = new Timer
+			{
+				Id = ObjectId.GenerateNewId(),
+				Time = time,
+				CallbackEvent = callbackEvent,
+				Env = env
+			};
+			this.timers[timer.Id] = timer;
+			this.timeId.Add(timer.Time, timer.Id);
+			return timer.Id;
+		}
+
+		public void Remove(ObjectId id)
+		{
+			Timer timer;
+			if (!this.timers.TryGetValue(id, out timer))
+			{
+				return;
+			}
+			this.timeId.Remove(timer.Time, timer.Id);
+		}
+
+		public Task<bool> Sleep(int time)
+		{
+			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
+			Env env = new Env();
+			env[EnvKey.SleepTimeout_TaskCompletionSource] = tcs;
+			this.Add(TimeHelper.Now() + time, EventType.SleepTimeout, env);
+			return tcs.Task;
+		}
+
+		public void Update()
+		{
+			long timeNow = TimeHelper.Now();
+
+			while (true)
+			{
+				KeyValuePair<long, List<ObjectId>> first = this.timeId.First;
+				if (first.Key > timeNow)
+				{
+					return;
+				}
+
+				List<ObjectId> timeoutId = first.Value;
+				this.timeId.Remove(first.Key);
+				foreach (ObjectId id in timeoutId)
+				{
+					Timer timer;
+					if (!this.timers.TryGetValue(id, out timer))
+					{
+						continue;
+					}
+					this.timers.Remove(id);
+#pragma warning disable 4014
+					World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(timer.CallbackEvent, timer.Env);
+#pragma warning restore 4014
+				}
+			}
+		}
+	}
 }

+ 69 - 69
CSharp/Game/Model/Component/UnitComponent.cs

@@ -1,70 +1,70 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Common.Base;
-using MongoDB.Bson;
-
-namespace Model
-{
-	public class UnitComponent: Component<World>
-	{
-		private readonly Dictionary<ObjectId, Unit> units = new Dictionary<ObjectId, Unit>();
-
-		private readonly Dictionary<int, Dictionary<ObjectId, Unit>> typeUnits =
-				new Dictionary<int, Dictionary<ObjectId, Unit>>();
-
-		public void Add(Unit unit)
-		{
-			this.units.Add(unit.Id, unit);
-			if (!this.typeUnits.ContainsKey(unit.Config.Type))
-			{
-				this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
-			}
-			this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
-		}
-
-		public Unit Get(ObjectId id)
-		{
-			Unit unit = null;
-			this.units.TryGetValue(id, out unit);
-			return unit;
-		}
-
-		public Unit[] GetOneType(int type)
-		{
-			Dictionary<ObjectId, Unit> oneTypeUnits = null;
-			if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
-			{
-				return new Unit[0];
-			}
-			return oneTypeUnits.Values.ToArray();
-		}
-
-		public bool Remove(Unit unit)
-		{
-			if (unit == null)
-			{
-				throw new ArgumentNullException(nameof(unit));
-			}
-			if (!this.units.Remove(unit.Id))
-			{
-				return false;
-			}
-			if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
-			{
-				return false;
-			}
-			return true;
-		}
-
-		public bool Remove(ObjectId id)
-		{
-			Unit unit = this.Get(id);
-			if (unit == null)
-			{
-				return false;
-			}
-			return this.Remove(unit);
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Common.Base;
+using MongoDB.Bson;
+
+namespace Model
+{
+	public class UnitComponent: Component<World>
+	{
+		private readonly Dictionary<ObjectId, Unit> units = new Dictionary<ObjectId, Unit>();
+
+		private readonly Dictionary<int, Dictionary<ObjectId, Unit>> typeUnits =
+				new Dictionary<int, Dictionary<ObjectId, Unit>>();
+
+		public void Add(Unit unit)
+		{
+			this.units.Add(unit.Id, unit);
+			if (!this.typeUnits.ContainsKey(unit.Config.Type))
+			{
+				this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
+			}
+			this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
+		}
+
+		public Unit Get(ObjectId id)
+		{
+			Unit unit = null;
+			this.units.TryGetValue(id, out unit);
+			return unit;
+		}
+
+		public Unit[] GetOneType(int type)
+		{
+			Dictionary<ObjectId, Unit> oneTypeUnits = null;
+			if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
+			{
+				return new Unit[0];
+			}
+			return oneTypeUnits.Values.ToArray();
+		}
+
+		public bool Remove(Unit unit)
+		{
+			if (unit == null)
+			{
+				throw new ArgumentNullException(nameof(unit));
+			}
+			if (!this.units.Remove(unit.Id))
+			{
+				return false;
+			}
+			if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
+			{
+				return false;
+			}
+			return true;
+		}
+
+		public bool Remove(ObjectId id)
+		{
+			Unit unit = this.Get(id);
+			if (unit == null)
+			{
+				return false;
+			}
+			return this.Remove(unit);
+		}
+	}
 }

+ 17 - 17
CSharp/Game/Model/Config/BuffConfig.cs

@@ -1,18 +1,18 @@
-using System.Collections.Generic;
-
-namespace Model
-{
-	public class BuffConfig: AConfig
-	{
-		public BuffType Type { get; set; }
-		public string Name { get; set; }
-		public long Duration { get; set; }
-		public int MaxStack { get; set; }
-		public List<int> Effects { get; set; }
-
-		public BuffConfig()
-		{
-			this.Effects = new List<int>();
-		}
-	}
+using System.Collections.Generic;
+
+namespace Model
+{
+	public class BuffConfig: AConfig
+	{
+		public BuffType Type { get; set; }
+		public string Name { get; set; }
+		public long Duration { get; set; }
+		public int MaxStack { get; set; }
+		public List<int> Effects { get; set; }
+
+		public BuffConfig()
+		{
+			this.Effects = new List<int>();
+		}
+	}
 }

+ 6 - 6
CSharp/Game/Model/Config/GlobalConfig.cs

@@ -1,7 +1,7 @@
-namespace Model
-{
-	public class GlobalConfig: AConfig
-	{
-		public int Type { get; set; }
-	}
+namespace Model
+{
+	public class GlobalConfig: AConfig
+	{
+		public int Type { get; set; }
+	}
 }

+ 10 - 10
CSharp/Game/Model/Config/ServerInfoConfig.cs

@@ -1,11 +1,11 @@
-namespace Model
-{
-	public class ServerInfoConfig: AConfig
-	{
-		public string Zone { get; set; }
-		public string Name { get; set; }
-		public string Host { get; set; }
-		public int Port { get; set; }
-		public ServerType ServerType { get; set; }
-	}
+namespace Model
+{
+	public class ServerInfoConfig: AConfig
+	{
+		public string Zone { get; set; }
+		public string Name { get; set; }
+		public string Host { get; set; }
+		public int Port { get; set; }
+		public ServerType ServerType { get; set; }
+	}
 }

+ 6 - 6
CSharp/Game/Model/Config/UnitConfig.cs

@@ -1,7 +1,7 @@
-namespace Model
-{
-	public class UnitConfig: AConfig
-	{
-		public int Type { get; set; }
-	}
+namespace Model
+{
+	public class UnitConfig: AConfig
+	{
+		public int Type { get; set; }
+	}
 }

+ 23 - 23
CSharp/Game/Model/ConfigAttribute.cs

@@ -1,24 +1,24 @@
-using System;
-
-namespace Model
-{
-	[AttributeUsage(AttributeTargets.Class)]
-	public class ConfigAttribute: Attribute
-	{
-		private ServerType ServerType { get; set; }
-
-		public ConfigAttribute(ServerType serverType)
-		{
-			this.ServerType = serverType;
-		}
-
-		public bool Contains(ServerType serverType)
-		{
-			if ((this.ServerType & serverType) == 0)
-			{
-				return false;
-			}
-			return true;
-		}
-	}
+using System;
+
+namespace Model
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class ConfigAttribute: Attribute
+	{
+		private ServerType ServerType { get; set; }
+
+		public ConfigAttribute(ServerType serverType)
+		{
+			this.ServerType = serverType;
+		}
+
+		public bool Contains(ServerType serverType)
+		{
+			if ((this.ServerType & serverType) == 0)
+			{
+				return false;
+			}
+			return true;
+		}
+	}
 }

+ 7 - 7
CSharp/Game/Model/Env.cs

@@ -1,8 +1,8 @@
-using Common.Base;
-
-namespace Model
-{
-	public class Env: Object
-	{
-	}
+using Common.Base;
+
+namespace Model
+{
+	public class Env: Object
+	{
+	}
 }

+ 17 - 17
CSharp/Game/Model/EnvKey.cs

@@ -1,18 +1,18 @@
-namespace Model
-{
-	public static class EnvKey
-	{
-		public const string Owner = "Owner";
-		public const string OwnerId = "OwnerId";
-		public const string Buff = "Buff";
-		public const string BuffId = "BuffId";
-		public const string MessageBytes = "MessageBytes";
-		public const string Message = "Message";
-		public const string Channel = "Channel";
-		public const string Opcode = "Opcode";
-		public const string MessageUnitId = "MessageUnitId";
-		public const string RpcRequestId = "RpcRequestId";
-
-		public const string SleepTimeout_TaskCompletionSource = "SleepTimeout_TaskCompletionSource";
-	}
+namespace Model
+{
+	public static class EnvKey
+	{
+		public const string Owner = "Owner";
+		public const string OwnerId = "OwnerId";
+		public const string Buff = "Buff";
+		public const string BuffId = "BuffId";
+		public const string MessageBytes = "MessageBytes";
+		public const string Message = "Message";
+		public const string Channel = "Channel";
+		public const string Opcode = "Opcode";
+		public const string MessageUnitId = "MessageUnitId";
+		public const string RpcRequestId = "RpcRequestId";
+
+		public const string SleepTimeout_TaskCompletionSource = "SleepTimeout_TaskCompletionSource";
+	}
 }

+ 9 - 9
CSharp/Game/Model/EventAttribute.cs

@@ -1,10 +1,10 @@
-namespace Model
-{
-	public class EventAttribute: AEventAttribute
-	{
-		public EventAttribute(EventType type, ServerType serverType)
-			: base(type, serverType)
-		{
-		}
-	}
+namespace Model
+{
+	public class EventAttribute: AEventAttribute
+	{
+		public EventAttribute(EventType type, ServerType serverType)
+			: base(type, serverType)
+		{
+		}
+	}
 }

+ 11 - 11
CSharp/Game/Model/EventType.cs

@@ -1,12 +1,12 @@
-namespace Model
-{
-	public enum EventType
-	{
-		BeforeAddBuff = 0,
-		AfterAddBuff = 1,
-		BeforeRemoveBuff = 2,
-		AfterRemoveBuff = 3,
-		BuffTimeout = 4,
-		SleepTimeout = 9,
-	}
+namespace Model
+{
+	public enum EventType
+	{
+		BeforeAddBuff = 0,
+		AfterAddBuff = 1,
+		BeforeRemoveBuff = 2,
+		AfterRemoveBuff = 3,
+		BuffTimeout = 4,
+		SleepTimeout = 9,
+	}
 }

+ 16 - 16
CSharp/Game/Model/FactoryAttribute.cs

@@ -1,17 +1,17 @@
-using System;
-
-namespace Model
-{
-	[AttributeUsage(AttributeTargets.Class)]
-	public class FactoryAttribute: Attribute
-	{
-		public Type ClassType { get; private set; }
-		public int Type { get; private set; }
-
-		public FactoryAttribute(Type classType, int type)
-		{
-			this.ClassType = classType;
-			this.Type = type;
-		}
-	}
+using System;
+
+namespace Model
+{
+	[AttributeUsage(AttributeTargets.Class)]
+	public class FactoryAttribute: Attribute
+	{
+		public Type ClassType { get; private set; }
+		public int Type { get; private set; }
+
+		public FactoryAttribute(Type classType, int type)
+		{
+			this.ClassType = classType;
+			this.Type = type;
+		}
+	}
 }

+ 26 - 26
CSharp/Game/Model/GameException.cs

@@ -1,26 +1,26 @@
-using System;
-
-namespace Model
-{
-	public class GameException : Exception
-	{
-		public GameException(string message): base(message)
-		{
-		}
-
-		public GameException(string format, params object[] args)
-			: base(string.Format(format, args))
-		{
-		}
-
-		public GameException(string message, Exception innerException)
-			: base(message, innerException)
-		{
-		}
-
-		public GameException(string format, Exception innerException, params object[] args)
-			: base(string.Format(format, args), innerException)
-		{
-		}
-	}
-}
+using System;
+
+namespace Model
+{
+	public class GameException : Exception
+	{
+		public GameException(string message): base(message)
+		{
+		}
+
+		public GameException(string format, params object[] args)
+			: base(string.Format(format, args))
+		{
+		}
+
+		public GameException(string message, Exception innerException)
+			: base(message, innerException)
+		{
+		}
+
+		public GameException(string format, Exception innerException, params object[] args)
+			: base(string.Format(format, args), innerException)
+		{
+		}
+	}
+}

+ 11 - 11
CSharp/Game/Model/IAssemblyLoader.cs

@@ -1,12 +1,12 @@
-using System.Reflection;
-
-namespace Model
-{
-	/// <summary>
-	/// World的Componet实现该接口,World.Load会调用Load方法
-	/// </summary>
-	public interface IAssemblyLoader
-	{
-		void Load(Assembly assembly);
-	}
+using System.Reflection;
+
+namespace Model
+{
+	/// <summary>
+	/// World的Componet实现该接口,World.Load会调用Load方法
+	/// </summary>
+	public interface IAssemblyLoader
+	{
+		void Load(Assembly assembly);
+	}
 }

+ 9 - 9
CSharp/Game/Model/ICategory.cs

@@ -1,10 +1,10 @@
-using System;
-using System.ComponentModel;
-
-namespace Model
-{
-	public interface ICategory: ISupportInitialize
-	{
-		Type ConfigType { get; }
-	}
+using System;
+using System.ComponentModel;
+
+namespace Model
+{
+	public interface ICategory: ISupportInitialize
+	{
+		Type ConfigType { get; }
+	}
 }

+ 8 - 8
CSharp/Game/Model/IConfigLoader.cs

@@ -1,9 +1,9 @@
-using System.Reflection;
-
-namespace Model
-{
-	internal interface IConfigLoader
-	{
-		void Load(Assembly assembly);
-	}
+using System.Reflection;
+
+namespace Model
+{
+	internal interface IConfigLoader
+	{
+		void Load(Assembly assembly);
+	}
 }

+ 8 - 8
CSharp/Game/Model/IFactory.cs

@@ -1,9 +1,9 @@
-using Common.Base;
-
-namespace Model
-{
-	public interface IFactory<out T> where T : Entity<T>
-	{
-		T Create(int configId);
-	}
+using Common.Base;
+
+namespace Model
+{
+	public interface IFactory<out T> where T : Entity<T>
+	{
+		T Create(int configId);
+	}
 }

+ 9 - 9
CSharp/Game/Model/IStart.cs

@@ -1,10 +1,10 @@
-namespace Model
-{
-	/// <summary>
-	/// World的Componet实现该接口后,会在World.Start时调用该Start方法
-	/// </summary>
-	internal interface IStart
-	{
-		void Start();
-	}
+namespace Model
+{
+	/// <summary>
+	/// World的Componet实现该接口后,会在World.Start时调用该Start方法
+	/// </summary>
+	internal interface IStart
+	{
+		void Start();
+	}
 }

+ 9 - 9
CSharp/Game/Model/IUpdate.cs

@@ -1,10 +1,10 @@
-namespace Model
-{
-	/// <summary>
-	/// 实现了该接口的World Componet会每帧刷新
-	/// </summary>
-	public interface IUpdate
-	{
-		void Update();
-	}
+namespace Model
+{
+	/// <summary>
+	/// 实现了该接口的World Componet会每帧刷新
+	/// </summary>
+	public interface IUpdate
+	{
+		void Update();
+	}
 }

+ 25 - 25
CSharp/Game/Model/MessageAttribute.cs

@@ -1,26 +1,26 @@
-using System;
-
-namespace Model
-{
-	/// <summary>
-	/// 搭配MessageComponent用来分发消息
-	/// </summary>
-	public class MessageAttribute: Attribute
-	{
-		private ServerType ServerType { get; set; }
-
-		public MessageAttribute(ServerType serverType)
-		{
-			this.ServerType = serverType;
-		}
-
-		public bool Contains(ServerType serverType)
-		{
-			if ((this.ServerType & serverType) == 0)
-			{
-				return false;
-			}
-			return true;
-		}
-	}
+using System;
+
+namespace Model
+{
+	/// <summary>
+	/// 搭配MessageComponent用来分发消息
+	/// </summary>
+	public class MessageAttribute: Attribute
+	{
+		private ServerType ServerType { get; set; }
+
+		public MessageAttribute(ServerType serverType)
+		{
+			this.ServerType = serverType;
+		}
+
+		public bool Contains(ServerType serverType)
+		{
+			if ((this.ServerType & serverType) == 0)
+			{
+				return false;
+			}
+			return true;
+		}
+	}
 }

+ 119 - 119
CSharp/Game/Model/Model.csproj

@@ -1,120 +1,120 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProjectGuid>{0608C0C1-F584-4092-AAF9-1E99A78E3703}</ProjectGuid>
-    <OutputType>Library</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>Model</RootNamespace>
-    <AssemblyName>Model</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-    <TargetFrameworkProfile />
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>..\..\Bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>..\..\Bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="CommandLine">
-      <HintPath>..\..\packages\CommandLineParser.1.9.71\lib\net45\CommandLine.dll</HintPath>
-    </Reference>
-    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
-      <Private>True</Private>
-    </Reference>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="ACategory.cs" />
-    <Compile Include="AConfig.cs" />
-    <Compile Include="AEventAttribute.cs" />
-    <Compile Include="BehaviorTree\BehaviorTree.cs" />
-    <Compile Include="BehaviorTree\Node.cs" />
-    <Compile Include="BehaviorTree\NodeAttribute.cs" />
-    <Compile Include="Buff.cs" />
-    <Compile Include="BuffType.cs" />
-    <Compile Include="Actor.cs" />
-    <Compile Include="Component\BehaviorTreeComponent.cs" />
-    <Compile Include="Component\BuffComponent.cs" />
-    <Compile Include="Component\ChannelUnitInfoComponent.cs" />
-    <Compile Include="Component\ConfigComponent.cs" />
-    <Compile Include="Component\MessageComponent.cs" />
-    <Compile Include="Component\EventComponent.cs" />
-    <Compile Include="Component\FactoryComponent.cs" />
-    <Compile Include="Component\GateNetworkComponent.cs" />
-    <Compile Include="Component\NetworkComponent.cs" />
-    <Compile Include="Component\TimerComponent.cs" />
-    <Compile Include="Component\ActorComponent.cs" />
-    <Compile Include="Component\UnitComponent.cs" />
-    <Compile Include="ConfigAttribute.cs" />
-    <Compile Include="Config\BuffConfig.cs" />
-    <Compile Include="Config\GlobalConfig.cs" />
-    <Compile Include="Config\ServerInfoConfig.cs" />
-    <Compile Include="Config\TreeConfig.cs" />
-    <Compile Include="Config\UnitConfig.cs" />
-    <Compile Include="Env.cs" />
-    <Compile Include="EnvKey.cs" />
-    <Compile Include="EventAttribute.cs" />
-    <Compile Include="EventType.cs" />
-    <Compile Include="FactoryAttribute.cs" />
-    <Compile Include="GameException.cs" />
-    <Compile Include="IAssemblyLoader.cs" />
-    <Compile Include="ICategory.cs" />
-    <Compile Include="IConfigLoader.cs" />
-    <Compile Include="IRegister.cs" />
-    <Compile Include="IEvent.cs" />
-    <Compile Include="IFactory.cs" />
-    <Compile Include="IStart.cs" />
-    <Compile Include="IUpdate.cs" />
-    <Compile Include="MessageAttribute.cs" />
-    <Compile Include="BehaviorTree\NodeType.cs" />
-    <Compile Include="Opcode.cs" />
-    <Compile Include="NumDefine.cs" />
-    <Compile Include="OpcodeHelper.cs" />
-    <Compile Include="Options.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="ServerType.cs" />
-    <Compile Include="Unit.cs" />
-    <Compile Include="UnitType.cs" />
-    <Compile Include="World.cs" />
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
-  <ItemGroup>
-    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
-      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
-      <Name>Common</Name>
-    </ProjectReference>
-    <ProjectReference Include="..\..\Platform\UNet\UNet.csproj">
-      <Project>{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}</Project>
-      <Name>UNet</Name>
-    </ProjectReference>
-    <ProjectReference Include="..\..\Platform\TNet\TNet.csproj">
-      <Project>{B1B78524-3F75-40D7-BF12-10B25A00C590}</Project>
-      <Name>TNet</Name>
-    </ProjectReference>
-  </ItemGroup>
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{0608C0C1-F584-4092-AAF9-1E99A78E3703}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Model</RootNamespace>
+    <AssemblyName>Model</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="CommandLine">
+      <HintPath>..\..\packages\CommandLineParser.1.9.71\lib\net45\CommandLine.dll</HintPath>
+    </Reference>
+    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="ACategory.cs" />
+    <Compile Include="AConfig.cs" />
+    <Compile Include="AEventAttribute.cs" />
+    <Compile Include="BehaviorTree\BehaviorTree.cs" />
+    <Compile Include="BehaviorTree\Node.cs" />
+    <Compile Include="BehaviorTree\NodeAttribute.cs" />
+    <Compile Include="Buff.cs" />
+    <Compile Include="BuffType.cs" />
+    <Compile Include="Actor.cs" />
+    <Compile Include="Component\BehaviorTreeComponent.cs" />
+    <Compile Include="Component\BuffComponent.cs" />
+    <Compile Include="Component\ChannelUnitInfoComponent.cs" />
+    <Compile Include="Component\ConfigComponent.cs" />
+    <Compile Include="Component\MessageComponent.cs" />
+    <Compile Include="Component\EventComponent.cs" />
+    <Compile Include="Component\FactoryComponent.cs" />
+    <Compile Include="Component\GateNetworkComponent.cs" />
+    <Compile Include="Component\NetworkComponent.cs" />
+    <Compile Include="Component\TimerComponent.cs" />
+    <Compile Include="Component\ActorComponent.cs" />
+    <Compile Include="Component\UnitComponent.cs" />
+    <Compile Include="ConfigAttribute.cs" />
+    <Compile Include="Config\BuffConfig.cs" />
+    <Compile Include="Config\GlobalConfig.cs" />
+    <Compile Include="Config\ServerInfoConfig.cs" />
+    <Compile Include="Config\TreeConfig.cs" />
+    <Compile Include="Config\UnitConfig.cs" />
+    <Compile Include="Env.cs" />
+    <Compile Include="EnvKey.cs" />
+    <Compile Include="EventAttribute.cs" />
+    <Compile Include="EventType.cs" />
+    <Compile Include="FactoryAttribute.cs" />
+    <Compile Include="GameException.cs" />
+    <Compile Include="IAssemblyLoader.cs" />
+    <Compile Include="ICategory.cs" />
+    <Compile Include="IConfigLoader.cs" />
+    <Compile Include="IRegister.cs" />
+    <Compile Include="IEvent.cs" />
+    <Compile Include="IFactory.cs" />
+    <Compile Include="IStart.cs" />
+    <Compile Include="IUpdate.cs" />
+    <Compile Include="MessageAttribute.cs" />
+    <Compile Include="BehaviorTree\NodeType.cs" />
+    <Compile Include="Opcode.cs" />
+    <Compile Include="NumDefine.cs" />
+    <Compile Include="OpcodeHelper.cs" />
+    <Compile Include="Options.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="ServerType.cs" />
+    <Compile Include="Unit.cs" />
+    <Compile Include="UnitType.cs" />
+    <Compile Include="World.cs" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+  <ItemGroup>
+    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
+      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\Platform\UNet\UNet.csproj">
+      <Project>{D3CEA64F-4D75-4DC9-B139-8D12EB4ACF8E}</Project>
+      <Name>UNet</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\..\Platform\TNet\TNet.csproj">
+      <Project>{B1B78524-3F75-40D7-BF12-10B25A00C590}</Project>
+      <Name>TNet</Name>
+    </ProjectReference>
+  </ItemGroup>
 </Project>

+ 5 - 5
CSharp/Game/Model/NumDefine.cs

@@ -1,6 +1,6 @@
-namespace Model
-{
-	public enum NumDefine
-	{
-	}
+namespace Model
+{
+	public enum NumDefine
+	{
+	}
 }

+ 8 - 8
CSharp/Game/Model/Opcode.cs

@@ -1,9 +1,9 @@
-namespace Model
-{
-	public enum Opcode: ushort
-	{
-		CMsgLogin = 1,
-		RpcResponse = 30000,
-		RpcException = 30001,
-	}
+namespace Model
+{
+	public enum Opcode: ushort
+	{
+		CMsgLogin = 1,
+		RpcResponse = 30000,
+		RpcException = 30001,
+	}
 }

+ 42 - 42
CSharp/Game/Model/Options.cs

@@ -1,43 +1,43 @@
-using System.Text;
-using CommandLine;
-using Common.Network;
-
-namespace Model
-{
-	public class Options
-	{
-		[Option('s', "serverType", Required = true, HelpText = "ServerType.")]
-		public ServerType ServerType { get; set; }
-
-		[Option('n', "name", Required = true, HelpText = "Name.")]
-		public string Name { get; set; }
-
-		[Option('h', "gateHost", Required = false, HelpText = "GateHost.")]
-		public string GateHost { get; set; }
-
-		[Option('p', "gatePort", Required = false, HelpText = "GatePort.")]
-		public int GatePort { get; set; }
-
-		[Option('h', "host", Required = true, HelpText = "Host.")]
-		public string Host { get; set; }
-
-		[Option('p', "port", Required = true, HelpText = "Port.")]
-		public int Port { get; set; }
-
-		[Option("protocol", Required = true, HelpText = "Protocol, tcp or udp.")]
-		public NetworkProtocol Protocol { get; set; }
-
-		[Option('v', HelpText = "Print details during execution.")]
-		public bool Verbose { get; set; }
-
-		[HelpOption]
-		public string GetUsage()
-		{
-			// this without using CommandLine.Text
-			StringBuilder usage = new StringBuilder();
-			usage.AppendLine("Quickstart Application 1.0");
-			usage.AppendLine("Read user manual for usage instructions...");
-			return usage.ToString();
-		}
-	}
+using System.Text;
+using CommandLine;
+using Common.Network;
+
+namespace Model
+{
+	public class Options
+	{
+		[Option('s', "serverType", Required = true, HelpText = "ServerType.")]
+		public ServerType ServerType { get; set; }
+
+		[Option('n', "name", Required = true, HelpText = "Name.")]
+		public string Name { get; set; }
+
+		[Option('h', "gateHost", Required = false, HelpText = "GateHost.")]
+		public string GateHost { get; set; }
+
+		[Option('p', "gatePort", Required = false, HelpText = "GatePort.")]
+		public int GatePort { get; set; }
+
+		[Option('h', "host", Required = true, HelpText = "Host.")]
+		public string Host { get; set; }
+
+		[Option('p', "port", Required = true, HelpText = "Port.")]
+		public int Port { get; set; }
+
+		[Option("protocol", Required = true, HelpText = "Protocol, tcp or udp.")]
+		public NetworkProtocol Protocol { get; set; }
+
+		[Option('v', HelpText = "Print details during execution.")]
+		public bool Verbose { get; set; }
+
+		[HelpOption]
+		public string GetUsage()
+		{
+			// this without using CommandLine.Text
+			StringBuilder usage = new StringBuilder();
+			usage.AppendLine("Quickstart Application 1.0");
+			usage.AppendLine("Read user manual for usage instructions...");
+			return usage.ToString();
+		}
+	}
 }

+ 38 - 38
CSharp/Game/Model/Properties/AssemblyInfo.cs

@@ -1,39 +1,39 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Model")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Model")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("b506d89a-5985-4165-93b4-e58e5c8718c3")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过以下
+// 特性集控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("Model")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("Model")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 使此程序集中的类型
+// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+// 则将该类型上的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("b506d89a-5985-4165-93b4-e58e5c8718c3")]
+
+// 程序集的版本信息由下面四个值组成: 
+//
+//      主版本
+//      次版本 
+//      生成号
+//      修订号
+//
+// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: 
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

+ 13 - 13
CSharp/Game/Model/ServerType.cs

@@ -1,14 +1,14 @@
-using System;
-
-namespace Model
-{
-	[Flags]
-	public enum ServerType
-	{
-		None = 0,
-		Realm = 1,
-		Gate = 2,
-		City = 4,
-		All = int.MaxValue,
-	}
+using System;
+
+namespace Model
+{
+	[Flags]
+	public enum ServerType
+	{
+		None = 0,
+		Realm = 1,
+		Gate = 2,
+		City = 4,
+		All = int.MaxValue,
+	}
 }

+ 24 - 24
CSharp/Game/Model/Unit.cs

@@ -1,25 +1,25 @@
-using Common.Base;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Model
-{
-	public class Unit: Entity<Unit>
-	{
-		[BsonElement]
-		private int configId { get; set; }
-
-		[BsonIgnore]
-		public UnitConfig Config
-		{
-			get
-			{
-				return World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(this.configId);
-			}
-		}
-
-		public Unit(int configId)
-		{
-			this.configId = configId;
-		}
-	}
+using Common.Base;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Model
+{
+	public class Unit: Entity<Unit>
+	{
+		[BsonElement]
+		private int configId { get; set; }
+
+		[BsonIgnore]
+		public UnitConfig Config
+		{
+			get
+			{
+				return World.Instance.GetComponent<ConfigComponent>().Get<UnitConfig>(this.configId);
+			}
+		}
+
+		public Unit(int configId)
+		{
+			this.configId = configId;
+		}
+	}
 }

+ 9 - 9
CSharp/Game/Model/UnitType.cs

@@ -1,10 +1,10 @@
-namespace Model
-{
-	public static class UnitType
-	{
-		public const int GatePlayer = 1;
-		public const int Player = 2;
-		public const int Npc = 3;
-		public const int Dog = 4;
-	}
+namespace Model
+{
+	public static class UnitType
+	{
+		public const int GatePlayer = 1;
+		public const int Player = 2;
+		public const int Npc = 3;
+		public const int Dog = 4;
+	}
 }

+ 81 - 81
CSharp/Game/Model/World.cs

@@ -1,82 +1,82 @@
-using System.Collections.Generic;
-using System.IO;
-using System.Reflection;
-using System.Threading;
-using Common.Base;
-
-namespace Model
-{
-	public class World: Entity<World>
-	{
-		private static readonly World instance = new World();
-
-		private Assembly assembly;
-
-		public static World Instance
-		{
-			get
-			{
-				return instance;
-			}
-		}
-
-		public Options Options { get; set; }
-
-		private readonly List<IUpdate> iUpdates = new List<IUpdate>();
-
-		private bool isStop;
-
-		private World()
-		{
-		}
-
-		public void Load()
-		{
-			this.assembly = Assembly.Load(File.ReadAllBytes(@"./Controller.dll"));
-
-			foreach (Component<World> component in this.GetComponents())
-			{
-				IAssemblyLoader assemblyLoader = component as IAssemblyLoader;
-				if (assemblyLoader != null)
-				{
-					assemblyLoader.Load(this.assembly);
-				}
-			}
-		}
-
-		public void Start()
-		{
-			this.Load();
-
-			foreach (Component<World> component in this.GetComponents())
-			{
-				IUpdate update = component as IUpdate;
-				if (update != null)
-				{
-					this.iUpdates.Add(update);
-				}
-
-				IStart start = component as IStart;
-				if (start != null)
-				{
-					start.Start();
-				}
-			}
-
-			// loop
-			while (!this.isStop)
-			{
-				Thread.Sleep(1);
-				foreach (IUpdate update in this.iUpdates)
-				{
-					update.Update();
-				}
-			}
-		}
-
-		public void Stop()
-		{
-			this.isStop = true;
-		}
-	}
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Threading;
+using Common.Base;
+
+namespace Model
+{
+	public class World: Entity<World>
+	{
+		private static readonly World instance = new World();
+
+		private Assembly assembly;
+
+		public static World Instance
+		{
+			get
+			{
+				return instance;
+			}
+		}
+
+		public Options Options { get; set; }
+
+		private readonly List<IUpdate> iUpdates = new List<IUpdate>();
+
+		private bool isStop;
+
+		private World()
+		{
+		}
+
+		public void Load()
+		{
+			this.assembly = Assembly.Load(File.ReadAllBytes(@"./Controller.dll"));
+
+			foreach (Component<World> component in this.GetComponents())
+			{
+				IAssemblyLoader assemblyLoader = component as IAssemblyLoader;
+				if (assemblyLoader != null)
+				{
+					assemblyLoader.Load(this.assembly);
+				}
+			}
+		}
+
+		public void Start()
+		{
+			this.Load();
+
+			foreach (Component<World> component in this.GetComponents())
+			{
+				IUpdate update = component as IUpdate;
+				if (update != null)
+				{
+					this.iUpdates.Add(update);
+				}
+
+				IStart start = component as IStart;
+				if (start != null)
+				{
+					start.Start();
+				}
+			}
+
+			// loop
+			while (!this.isStop)
+			{
+				Thread.Sleep(1);
+				foreach (IUpdate update in this.iUpdates)
+				{
+					update.Update();
+				}
+			}
+		}
+
+		public void Stop()
+		{
+			this.isStop = true;
+		}
+	}
 }

+ 35 - 35
CSharp/Platform/Common/Base/Component.cs

@@ -1,36 +1,36 @@
-using System;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Common.Base
-{
-	/// <summary>
-	/// Component的Id与Owner Entity Id一样
-	/// </summary>
-	public abstract class Component<T>: Object where T : Entity<T>
-	{
-		private T owner;
-
-		[BsonIgnore]
-		public T Owner
-		{
-			get
-			{
-				return this.owner;
-			}
-			set
-			{
-				this.owner = value;
-				this.Id = this.owner.Id;
-			}
-		}
-
-		/// <summary>
-		/// 用于父类的Component需要重写此方法
-		/// </summary>
-		/// <returns></returns>
-		public virtual Type GetComponentType()
-		{
-			return this.GetType();
-		}
-	}
+using System;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Common.Base
+{
+	/// <summary>
+	/// Component的Id与Owner Entity Id一样
+	/// </summary>
+	public abstract class Component<T>: Object where T : Entity<T>
+	{
+		private T owner;
+
+		[BsonIgnore]
+		public T Owner
+		{
+			get
+			{
+				return this.owner;
+			}
+			set
+			{
+				this.owner = value;
+				this.Id = this.owner.Id;
+			}
+		}
+
+		/// <summary>
+		/// 用于父类的Component需要重写此方法
+		/// </summary>
+		/// <returns></returns>
+		public virtual Type GetComponentType()
+		{
+			return this.GetType();
+		}
+	}
 }

+ 118 - 118
CSharp/Platform/Common/Base/Entity.cs

@@ -1,119 +1,119 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Common.Helper;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Common.Base
-{
-	public abstract class Entity<T>: Object where T : Entity<T>
-	{
-		[BsonElement, BsonIgnoreIfNull]
-		private HashSet<Component<T>> components;
-
-		private Dictionary<Type, Component<T>> componentDict = new Dictionary<Type, Component<T>>();
-
-		protected Entity()
-		{
-		}
-
-		protected Entity(ObjectId id): base(id)
-		{
-		}
-
-		public T Clone()
-		{
-			return MongoHelper.FromBson<T>(MongoHelper.ToBson(this));
-		}
-
-		public K AddComponent<K>() where K : Component<T>, new()
-		{
-			K component = (K) Activator.CreateInstance(typeof (K));
-			component.Owner = (T) this;
-
-			if (this.componentDict.ContainsKey(component.GetComponentType()))
-			{
-				throw new Exception($"AddComponent, component already exist, id: {this.Id}, component: {typeof (K).Name}");
-			}
-
-			if (this.components == null)
-			{
-				this.components = new HashSet<Component<T>>();
-			}
-
-			this.components.Add(component);
-			this.componentDict.Add(component.GetComponentType(), component);
-			return component;
-		}
-
-		public void AddComponent(Component<T> component)
-		{
-			if (this.componentDict.ContainsKey(component.GetComponentType()))
-			{
-				throw new Exception($"AddComponent, component already exist, id: {this.Id}, component: {component.GetComponentType().Name}");
-			}
-
-			if (this.components == null)
-			{
-				this.components = new HashSet<Component<T>>();
-			}
-			this.components.Add(component);
-			this.componentDict.Add(component.GetComponentType(), component);
-		}
-
-		public void RemoveComponent<K>() where K : Component<T>
-		{
-			Component<T> component;
-			if (!this.componentDict.TryGetValue(typeof (K), out component))
-			{
-				throw new Exception($"RemoveComponent, component not exist, id: {this.Id}, component: {typeof (K).Name}");
-			}
-
-			this.components.Remove(component);
-			this.componentDict.Remove(typeof (K));
-
-			if (this.components.Count == 0)
-			{
-				this.components = null;
-			}
-		}
-
-		public K GetComponent<K>() where K : Component<T>
-		{
-			Component<T> component;
-			if (!this.componentDict.TryGetValue(typeof (K), out component))
-			{
-				return default (K);
-			}
-			return (K) component;
-		}
-
-		public Component<T>[] GetComponents()
-		{
-			return this.components.ToArray();
-		}
-
-		public override void BeginInit()
-		{
-			base.BeginInit();
-			this.components = new HashSet<Component<T>>();
-			this.componentDict = new Dictionary<Type, Component<T>>();
-		}
-
-		public override void EndInit()
-		{
-			base.EndInit();
-			if (this.components.Count == 0)
-			{
-				this.components = null;
-				return;
-			}
-			foreach (Component<T> component in this.components)
-			{
-				component.Owner = (T) this;
-				this.componentDict.Add(component.GetComponentType(), component);
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Common.Helper;
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Common.Base
+{
+	public abstract class Entity<T>: Object where T : Entity<T>
+	{
+		[BsonElement, BsonIgnoreIfNull]
+		private HashSet<Component<T>> components;
+
+		private Dictionary<Type, Component<T>> componentDict = new Dictionary<Type, Component<T>>();
+
+		protected Entity()
+		{
+		}
+
+		protected Entity(ObjectId id): base(id)
+		{
+		}
+
+		public T Clone()
+		{
+			return MongoHelper.FromBson<T>(MongoHelper.ToBson(this));
+		}
+
+		public K AddComponent<K>() where K : Component<T>, new()
+		{
+			K component = (K) Activator.CreateInstance(typeof (K));
+			component.Owner = (T) this;
+
+			if (this.componentDict.ContainsKey(component.GetComponentType()))
+			{
+				throw new Exception($"AddComponent, component already exist, id: {this.Id}, component: {typeof (K).Name}");
+			}
+
+			if (this.components == null)
+			{
+				this.components = new HashSet<Component<T>>();
+			}
+
+			this.components.Add(component);
+			this.componentDict.Add(component.GetComponentType(), component);
+			return component;
+		}
+
+		public void AddComponent(Component<T> component)
+		{
+			if (this.componentDict.ContainsKey(component.GetComponentType()))
+			{
+				throw new Exception($"AddComponent, component already exist, id: {this.Id}, component: {component.GetComponentType().Name}");
+			}
+
+			if (this.components == null)
+			{
+				this.components = new HashSet<Component<T>>();
+			}
+			this.components.Add(component);
+			this.componentDict.Add(component.GetComponentType(), component);
+		}
+
+		public void RemoveComponent<K>() where K : Component<T>
+		{
+			Component<T> component;
+			if (!this.componentDict.TryGetValue(typeof (K), out component))
+			{
+				throw new Exception($"RemoveComponent, component not exist, id: {this.Id}, component: {typeof (K).Name}");
+			}
+
+			this.components.Remove(component);
+			this.componentDict.Remove(typeof (K));
+
+			if (this.components.Count == 0)
+			{
+				this.components = null;
+			}
+		}
+
+		public K GetComponent<K>() where K : Component<T>
+		{
+			Component<T> component;
+			if (!this.componentDict.TryGetValue(typeof (K), out component))
+			{
+				return default (K);
+			}
+			return (K) component;
+		}
+
+		public Component<T>[] GetComponents()
+		{
+			return this.components.ToArray();
+		}
+
+		public override void BeginInit()
+		{
+			base.BeginInit();
+			this.components = new HashSet<Component<T>>();
+			this.componentDict = new Dictionary<Type, Component<T>>();
+		}
+
+		public override void EndInit()
+		{
+			base.EndInit();
+			if (this.components.Count == 0)
+			{
+				this.components = null;
+				return;
+			}
+			foreach (Component<T> component in this.components)
+			{
+				component.Owner = (T) this;
+				this.componentDict.Add(component.GetComponentType(), component);
+			}
+		}
+	}
 }

+ 119 - 119
CSharp/Platform/Common/Base/MultiMap.cs

@@ -1,120 +1,120 @@
-using System.Collections.Generic;
-using System.Linq;
-
-namespace Common.Base
-{
-	public class MultiMap<T, K>
-	{
-		private readonly SortedDictionary<T, List<K>> dictionary = new SortedDictionary<T, List<K>>();
-
-		public SortedDictionary<T, List<K>>.KeyCollection Keys
-		{
-			get
-			{
-				return this.dictionary.Keys;
-			}
-		}
-
-		public void Add(T t, K k)
-		{
-			List<K> list;
-			this.dictionary.TryGetValue(t, out list);
-			if (list == null)
-			{
-				list = new List<K>();
-			}
-			list.Add(k);
-			this.dictionary[t] = list;
-		}
-
-		public KeyValuePair<T, List<K>> First
-		{
-			get
-			{
-				return dictionary.First();
-			}
-		}
-
-		public bool Remove(T t, K k)
-		{
-			List<K> list;
-			this.dictionary.TryGetValue(t, out list);
-			if (list == null)
-			{
-				return false;
-			}
-			if (!list.Remove(k))
-			{
-				return false;
-			}
-			if (list.Count == 0)
-			{
-				this.dictionary.Remove(t);
-			}
-			return true;
-		}
-
-		public bool Remove(T t)
-		{
-			return this.dictionary.Remove(t);
-		}
-
-		/// <summary>
-		/// 不返回内部的list,copy一份出来
-		/// </summary>
-		/// <param name="t"></param>
-		/// <returns></returns>
-		public K[] GetAll(T t)
-		{
-			List<K> list;
-			this.dictionary.TryGetValue(t, out list);
-			if (list == null)
-			{
-				return new K[0];
-			}
-			var newList = new List<K>();
-			foreach (K k in list)
-			{
-				newList.Add(k);
-			}
-			return newList.ToArray();
-		}
-
-		/// <summary>
-		/// 返回内部的list
-		/// </summary>
-		/// <param name="t"></param>
-		/// <returns></returns>
-		public List<K> this[T t]
-		{
-			get
-			{
-				List<K> list;
-				this.dictionary.TryGetValue(t, out list);
-				return list;
-			}
-		}
-
-		public K GetOne(T t)
-		{
-			List<K> list;
-			this.dictionary.TryGetValue(t, out list);
-			if ((list != null) && (list.Count > 0))
-			{
-				return list[0];
-			}
-			return default(K);
-		}
-
-		public bool Contains(T t, K k)
-		{
-			List<K> list;
-			this.dictionary.TryGetValue(t, out list);
-			if (list == null)
-			{
-				return false;
-			}
-			return list.Contains(k);
-		}
-	}
+using System.Collections.Generic;
+using System.Linq;
+
+namespace Common.Base
+{
+	public class MultiMap<T, K>
+	{
+		private readonly SortedDictionary<T, List<K>> dictionary = new SortedDictionary<T, List<K>>();
+
+		public SortedDictionary<T, List<K>>.KeyCollection Keys
+		{
+			get
+			{
+				return this.dictionary.Keys;
+			}
+		}
+
+		public void Add(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				list = new List<K>();
+			}
+			list.Add(k);
+			this.dictionary[t] = list;
+		}
+
+		public KeyValuePair<T, List<K>> First
+		{
+			get
+			{
+				return dictionary.First();
+			}
+		}
+
+		public bool Remove(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return false;
+			}
+			if (!list.Remove(k))
+			{
+				return false;
+			}
+			if (list.Count == 0)
+			{
+				this.dictionary.Remove(t);
+			}
+			return true;
+		}
+
+		public bool Remove(T t)
+		{
+			return this.dictionary.Remove(t);
+		}
+
+		/// <summary>
+		/// 不返回内部的list,copy一份出来
+		/// </summary>
+		/// <param name="t"></param>
+		/// <returns></returns>
+		public K[] GetAll(T t)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return new K[0];
+			}
+			var newList = new List<K>();
+			foreach (K k in list)
+			{
+				newList.Add(k);
+			}
+			return newList.ToArray();
+		}
+
+		/// <summary>
+		/// 返回内部的list
+		/// </summary>
+		/// <param name="t"></param>
+		/// <returns></returns>
+		public List<K> this[T t]
+		{
+			get
+			{
+				List<K> list;
+				this.dictionary.TryGetValue(t, out list);
+				return list;
+			}
+		}
+
+		public K GetOne(T t)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if ((list != null) && (list.Count > 0))
+			{
+				return list[0];
+			}
+			return default(K);
+		}
+
+		public bool Contains(T t, K k)
+		{
+			List<K> list;
+			this.dictionary.TryGetValue(t, out list);
+			if (list == null)
+			{
+				return false;
+			}
+			return list.Contains(k);
+		}
+	}
 }

+ 119 - 119
CSharp/Platform/Common/Base/Object.cs

@@ -1,120 +1,120 @@
-using System.Collections;
-using System.Collections.Generic;
-using System.ComponentModel;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-
-namespace Common.Base
-{
-	public abstract class Object: ISupportInitialize
-	{
-		[BsonId]
-		public ObjectId Id { get; protected set; }
-
-		[BsonElement, BsonIgnoreIfNull]
-		private Dictionary<string, object> values;
-
-		protected Object()
-		{
-			this.Id = ObjectId.GenerateNewId();
-		}
-
-		protected Object(ObjectId id)
-		{
-			this.Id = id;
-		}
-
-		public virtual void BeginInit()
-		{
-			if (this.values == null)
-			{
-				this.values = new Dictionary<string, object>();
-			}
-		}
-
-		public virtual void EndInit()
-		{
-			if (this.values.Count == 0)
-			{
-				this.values = null;
-			}
-		}
-
-		public object this[string key]
-		{
-			get
-			{
-				return this.values[key];
-			}
-			set
-			{
-				if (this.values == null)
-				{
-					this.values = new Dictionary<string, object>();
-				}
-				this.values[key] = value;
-			}
-		}
-
-		public T Get<T>(string key)
-		{
-			if (!this.values.ContainsKey(key))
-			{
-				return default(T);
-			}
-			return (T) this.values[key];
-		}
-
-		public T Get<T>()
-		{
-			return this.Get<T>(typeof (T).Name);
-		}
-
-		public void Set(string key, object obj)
-		{
-			if (this.values == null)
-			{
-				this.values = new Dictionary<string, object>();
-			}
-			this.values[key] = obj;
-		}
-
-		public void Set<T>(T obj)
-		{
-			if (this.values == null)
-			{
-				this.values = new Dictionary<string, object>();
-			}
-			this.values[typeof (T).Name] = obj;
-		}
-
-		public bool ContainKey(string key)
-		{
-			return this.values.ContainsKey(key);
-		}
-
-		public bool Remove(string key)
-		{
-			bool ret = this.values.Remove(key);
-			if (this.values.Count == 0)
-			{
-				this.values = null;
-			}
-			return ret;
-		}
-
-		public void Add(string key, object value)
-		{
-			if (this.values == null)
-			{
-				this.values = new Dictionary<string, object>();
-			}
-			this.values.Add(key, value);
-		}
-
-		public IEnumerator GetEnumerator()
-		{
-			return this.values.GetEnumerator();
-		}
-	}
+using System.Collections;
+using System.Collections.Generic;
+using System.ComponentModel;
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Common.Base
+{
+	public abstract class Object: ISupportInitialize
+	{
+		[BsonId]
+		public ObjectId Id { get; protected set; }
+
+		[BsonElement, BsonIgnoreIfNull]
+		private Dictionary<string, object> values;
+
+		protected Object()
+		{
+			this.Id = ObjectId.GenerateNewId();
+		}
+
+		protected Object(ObjectId id)
+		{
+			this.Id = id;
+		}
+
+		public virtual void BeginInit()
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+		}
+
+		public virtual void EndInit()
+		{
+			if (this.values.Count == 0)
+			{
+				this.values = null;
+			}
+		}
+
+		public object this[string key]
+		{
+			get
+			{
+				return this.values[key];
+			}
+			set
+			{
+				if (this.values == null)
+				{
+					this.values = new Dictionary<string, object>();
+				}
+				this.values[key] = value;
+			}
+		}
+
+		public T Get<T>(string key)
+		{
+			if (!this.values.ContainsKey(key))
+			{
+				return default(T);
+			}
+			return (T) this.values[key];
+		}
+
+		public T Get<T>()
+		{
+			return this.Get<T>(typeof (T).Name);
+		}
+
+		public void Set(string key, object obj)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values[key] = obj;
+		}
+
+		public void Set<T>(T obj)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values[typeof (T).Name] = obj;
+		}
+
+		public bool ContainKey(string key)
+		{
+			return this.values.ContainsKey(key);
+		}
+
+		public bool Remove(string key)
+		{
+			bool ret = this.values.Remove(key);
+			if (this.values.Count == 0)
+			{
+				this.values = null;
+			}
+			return ret;
+		}
+
+		public void Add(string key, object value)
+		{
+			if (this.values == null)
+			{
+				this.values = new Dictionary<string, object>();
+			}
+			this.values.Add(key, value);
+		}
+
+		public IEnumerator GetEnumerator()
+		{
+			return this.values.GetEnumerator();
+		}
+	}
 }

+ 46 - 46
CSharp/Platform/Common/Base/QueueDictionary.cs

@@ -1,47 +1,47 @@
-using System.Collections.Generic;
-
-namespace Common.Base
-{
-	public class QueueDictionary<T, K>
-	{
-		private readonly List<T> list = new List<T>();
-		private readonly Dictionary<T, K> dictionary = new Dictionary<T, K>();
-
-		public void Add(T t, K k)
-		{
-			this.list.Add(t);
-			this.dictionary.Add(t, k);
-		}
-
-		public bool Remove(T t)
-		{
-			this.list.Remove(t);
-			this.dictionary.Remove(t);
-			return true;
-		}
-
-		public int Count
-		{
-			get
-			{
-				return this.list.Count;
-			}
-		}
-
-		public T FirstKey
-		{
-			get
-			{
-				return this.list[0];
-			}
-		}
-
-		public K this[T t]
-		{
-			get
-			{
-				return this.dictionary[t];
-			}
-		}
-	}
+using System.Collections.Generic;
+
+namespace Common.Base
+{
+	public class QueueDictionary<T, K>
+	{
+		private readonly List<T> list = new List<T>();
+		private readonly Dictionary<T, K> dictionary = new Dictionary<T, K>();
+
+		public void Add(T t, K k)
+		{
+			this.list.Add(t);
+			this.dictionary.Add(t, k);
+		}
+
+		public bool Remove(T t)
+		{
+			this.list.Remove(t);
+			this.dictionary.Remove(t);
+			return true;
+		}
+
+		public int Count
+		{
+			get
+			{
+				return this.list.Count;
+			}
+		}
+
+		public T FirstKey
+		{
+			get
+			{
+				return this.list[0];
+			}
+		}
+
+		public K this[T t]
+		{
+			get
+			{
+				return this.dictionary[t];
+			}
+		}
+	}
 }

+ 88 - 88
CSharp/Platform/Common/Base/TimerManager.cs

@@ -1,89 +1,89 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Threading.Tasks;
-using Common.Helper;
-using MongoDB.Bson;
-
-namespace Common.Base
-{
-	public class TimerManager
-	{
-		private class Timer
-		{
-			public ObjectId Id { get; set; }
-			public long Time { get; set; }
-			public Action Action { get; set; }
-		}
-
-		private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
-
-		/// <summary>
-		/// key: time, value: timer id
-		/// </summary>
-		private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
-
-		private readonly Queue<long> timeoutTimer = new Queue<long>();
-
-		public ObjectId Add(long time, Action action)
-		{
-			Timer timer = new Timer { Id = ObjectId.GenerateNewId(), Time = time, Action = action };
-			this.timers[timer.Id] = timer;
-			this.timeId.Add(timer.Time, timer.Id);
-			return timer.Id;
-		}
-
-		public void Remove(ObjectId id)
-		{
-			Timer timer;
-			if (!this.timers.TryGetValue(id, out timer))
-			{
-				return;
-			}
-			this.timers.Remove(timer.Id);
-			this.timeId.Remove(timer.Time, timer.Id);
-		}
-
-		public Task<bool> Sleep(int time)
-		{
-			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
-			this.Add(TimeHelper.Now() + time, () => { tcs.SetResult(true); });
-			return tcs.Task;
-		}
-
-		public Task<bool> Sleep(int time, CancellationToken token)
-		{
-			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
-			ObjectId id = this.Add(TimeHelper.Now() + time, () => { tcs.SetResult(true); });
-			token.Register(() => { this.Remove(id); });
-			return tcs.Task;
-		}
-
-		public void Refresh()
-		{
-			long timeNow = TimeHelper.Now();
-
-			while (true)
-			{
-				KeyValuePair<long, List<ObjectId>> first = this.timeId.First;
-				if (first.Key > timeNow)
-				{
-					return;
-				}
-
-				List<ObjectId> timeoutId = first.Value;
-				this.timeId.Remove(first.Key);
-				foreach (ObjectId id in timeoutId)
-				{
-					Timer timer;
-					if (!this.timers.TryGetValue(id, out timer))
-					{
-						continue;
-					}
-					this.timers.Remove(id);
-					timer.Action();
-				}
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using Common.Helper;
+using MongoDB.Bson;
+
+namespace Common.Base
+{
+	public class TimerManager
+	{
+		private class Timer
+		{
+			public ObjectId Id { get; set; }
+			public long Time { get; set; }
+			public Action Action { get; set; }
+		}
+
+		private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
+
+		/// <summary>
+		/// key: time, value: timer id
+		/// </summary>
+		private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
+
+		private readonly Queue<long> timeoutTimer = new Queue<long>();
+
+		public ObjectId Add(long time, Action action)
+		{
+			Timer timer = new Timer { Id = ObjectId.GenerateNewId(), Time = time, Action = action };
+			this.timers[timer.Id] = timer;
+			this.timeId.Add(timer.Time, timer.Id);
+			return timer.Id;
+		}
+
+		public void Remove(ObjectId id)
+		{
+			Timer timer;
+			if (!this.timers.TryGetValue(id, out timer))
+			{
+				return;
+			}
+			this.timers.Remove(timer.Id);
+			this.timeId.Remove(timer.Time, timer.Id);
+		}
+
+		public Task<bool> Sleep(int time)
+		{
+			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
+			this.Add(TimeHelper.Now() + time, () => { tcs.SetResult(true); });
+			return tcs.Task;
+		}
+
+		public Task<bool> Sleep(int time, CancellationToken token)
+		{
+			TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
+			ObjectId id = this.Add(TimeHelper.Now() + time, () => { tcs.SetResult(true); });
+			token.Register(() => { this.Remove(id); });
+			return tcs.Task;
+		}
+
+		public void Refresh()
+		{
+			long timeNow = TimeHelper.Now();
+
+			while (true)
+			{
+				KeyValuePair<long, List<ObjectId>> first = this.timeId.First;
+				if (first.Key > timeNow)
+				{
+					return;
+				}
+
+				List<ObjectId> timeoutId = first.Value;
+				this.timeId.Remove(first.Key);
+				foreach (ObjectId id in timeoutId)
+				{
+					Timer timer;
+					if (!this.timers.TryGetValue(id, out timer))
+					{
+						continue;
+					}
+					this.timers.Remove(id);
+					timer.Action();
+				}
+			}
+		}
+	}
 }

+ 87 - 87
CSharp/Platform/Common/Common.csproj

@@ -1,88 +1,88 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProjectGuid>{F06B995E-6508-4C5C-A396-554316C9215D}</ProjectGuid>
-    <OutputType>Library</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>Common</RootNamespace>
-    <AssemblyName>Common</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-    <TargetFrameworkProfile />
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>..\..\Bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>..\..\Bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
-      <Private>True</Private>
-    </Reference>
-    <Reference Include="NLog">
-      <HintPath>..\..\packages\NLog.4.1.1\lib\net45\NLog.dll</HintPath>
-    </Reference>
-    <Reference Include="protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67, processorArchitecture=MSIL">
-      <SpecificVersion>False</SpecificVersion>
-      <HintPath>..\..\packages\protobuf-net.2.0.0.668\lib\net40\protobuf-net.dll</HintPath>
-    </Reference>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-    <Reference Include="System.Numerics" />
-    <Reference Include="System.Xml" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="Base\Component.cs" />
-    <Compile Include="Base\Entity.cs" />
-    <Compile Include="Base\MultiMap.cs" />
-    <Compile Include="Base\Object.cs" />
-    <Compile Include="Base\QueueDictionary.cs" />
-    <Compile Include="Base\TimerManager.cs" />
-    <Compile Include="Helper\BigIntegerHelper.cs" />
-    <Compile Include="Helper\ByteHelper.cs" />
-    <Compile Include="Helper\EnumHelper.cs" />
-    <Compile Include="Helper\LoaderHelper.cs" />
-    <Compile Include="Helper\MongoHelper.cs" />
-    <Compile Include="Helper\ProtobufHelper.cs" />
-    <Compile Include="Helper\RandomHelper.cs" />
-    <Compile Include="Helper\StringHelper.cs" />
-    <Compile Include="Helper\TimeHelper.cs" />
-    <Compile Include="Helper\XmlHelper.cs" />
-    <Compile Include="Hooks\Native.cs" />
-    <Compile Include="Logger\ALogDecorater.cs" />
-    <Compile Include="Logger\ILog.cs" />
-    <Compile Include="Logger\Log.cs" />
-    <Compile Include="Logger\NLogAdapter.cs" />
-    <Compile Include="Logger\StackInfoDecorater.cs" />
-    <Compile Include="Network\AChannel.cs" />
-    <Compile Include="Network\IService.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <None Include="Helper\Packages.config" />
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{F06B995E-6508-4C5C-A396-554316C9215D}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>Common</RootNamespace>
+    <AssemblyName>Common</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="NLog">
+      <HintPath>..\..\packages\NLog.4.1.1\lib\net45\NLog.dll</HintPath>
+    </Reference>
+    <Reference Include="protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67, processorArchitecture=MSIL">
+      <SpecificVersion>False</SpecificVersion>
+      <HintPath>..\..\packages\protobuf-net.2.0.0.668\lib\net40\protobuf-net.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+    <Reference Include="System.Numerics" />
+    <Reference Include="System.Xml" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Base\Component.cs" />
+    <Compile Include="Base\Entity.cs" />
+    <Compile Include="Base\MultiMap.cs" />
+    <Compile Include="Base\Object.cs" />
+    <Compile Include="Base\QueueDictionary.cs" />
+    <Compile Include="Base\TimerManager.cs" />
+    <Compile Include="Helper\BigIntegerHelper.cs" />
+    <Compile Include="Helper\ByteHelper.cs" />
+    <Compile Include="Helper\EnumHelper.cs" />
+    <Compile Include="Helper\LoaderHelper.cs" />
+    <Compile Include="Helper\MongoHelper.cs" />
+    <Compile Include="Helper\ProtobufHelper.cs" />
+    <Compile Include="Helper\RandomHelper.cs" />
+    <Compile Include="Helper\StringHelper.cs" />
+    <Compile Include="Helper\TimeHelper.cs" />
+    <Compile Include="Helper\XmlHelper.cs" />
+    <Compile Include="Hooks\Native.cs" />
+    <Compile Include="Logger\ALogDecorater.cs" />
+    <Compile Include="Logger\ILog.cs" />
+    <Compile Include="Logger\Log.cs" />
+    <Compile Include="Logger\NLogAdapter.cs" />
+    <Compile Include="Logger\StackInfoDecorater.cs" />
+    <Compile Include="Network\AChannel.cs" />
+    <Compile Include="Network\IService.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="Helper\Packages.config" />
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
 </Project>

+ 79 - 79
CSharp/Platform/Common/Helper/BigIntegerHelper.cs

@@ -1,80 +1,80 @@
-using System;
-using System.Numerics;
-
-namespace Common.Helper
-{
-	public static class BigIntegerHelper
-	{
-		public static BigInteger RandBigInteger(int byteNum)
-		{
-			var bigIntegerBytes = new byte[byteNum];
-			Random random = new Random();
-			random.NextBytes(bigIntegerBytes);
-			BigInteger bigInteger = new BigInteger(bigIntegerBytes);
-			return bigInteger;
-		}
-
-		public static BigInteger RandUnsignedBigInteger(int byteNum)
-		{
-			var bigIntegerBytes = new byte[byteNum];
-			Random random = new Random();
-			random.NextBytes(bigIntegerBytes);
-			//bigIntegerBytes = "C6DFEDA1EAAC7417A191EE5EC6062CE9546614".HexToBytes().Reverse();
-
-			return bigIntegerBytes.ToUBigInteger();
-		}
-
-		public static BigInteger ToBigInteger(this byte[] bytes)
-		{
-			return new BigInteger(bytes);
-		}
-
-		public static BigInteger ToUBigInteger(this byte[] bytes)
-		{
-			var dst = new byte[bytes.Length + 1];
-			Array.Copy(bytes, dst, bytes.Length);
-			return new BigInteger(dst);
-		}
-
-		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
-		{
-			var result = bigInteger.ToByteArray();
-			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
-			{
-				Array.Resize(ref result, result.Length - 1);
-			}
-			return result;
-		}
-
-		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger, int length)
-		{
-			var result = bigInteger.ToByteArray();
-			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
-			{
-				Array.Resize(ref result, result.Length - 1);
-			}
-			if (length > result.Length)
-			{
-				Array.Resize(ref result, length);
-			}
-			return result;
-		}
-
-		/// <summary>
-		/// 返回非负值
-		/// </summary>
-		/// <param name="value"></param>
-		/// <param name="exponent"></param>
-		/// <param name="modulus"></param>
-		/// <returns></returns>
-		public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
-		{
-			BigInteger result = BigInteger.ModPow(value, exponent, modulus);
-			if (result < 0)
-			{
-				result += modulus;
-			}
-			return result;
-		}
-	}
+using System;
+using System.Numerics;
+
+namespace Common.Helper
+{
+	public static class BigIntegerHelper
+	{
+		public static BigInteger RandBigInteger(int byteNum)
+		{
+			var bigIntegerBytes = new byte[byteNum];
+			Random random = new Random();
+			random.NextBytes(bigIntegerBytes);
+			BigInteger bigInteger = new BigInteger(bigIntegerBytes);
+			return bigInteger;
+		}
+
+		public static BigInteger RandUnsignedBigInteger(int byteNum)
+		{
+			var bigIntegerBytes = new byte[byteNum];
+			Random random = new Random();
+			random.NextBytes(bigIntegerBytes);
+			//bigIntegerBytes = "C6DFEDA1EAAC7417A191EE5EC6062CE9546614".HexToBytes().Reverse();
+
+			return bigIntegerBytes.ToUBigInteger();
+		}
+
+		public static BigInteger ToBigInteger(this byte[] bytes)
+		{
+			return new BigInteger(bytes);
+		}
+
+		public static BigInteger ToUBigInteger(this byte[] bytes)
+		{
+			var dst = new byte[bytes.Length + 1];
+			Array.Copy(bytes, dst, bytes.Length);
+			return new BigInteger(dst);
+		}
+
+		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger)
+		{
+			var result = bigInteger.ToByteArray();
+			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
+			{
+				Array.Resize(ref result, result.Length - 1);
+			}
+			return result;
+		}
+
+		public static byte[] ToUBigIntegerArray(this BigInteger bigInteger, int length)
+		{
+			var result = bigInteger.ToByteArray();
+			if (result[result.Length - 1] == 0 && (result.Length % 0x10) != 0)
+			{
+				Array.Resize(ref result, result.Length - 1);
+			}
+			if (length > result.Length)
+			{
+				Array.Resize(ref result, length);
+			}
+			return result;
+		}
+
+		/// <summary>
+		/// 返回非负值
+		/// </summary>
+		/// <param name="value"></param>
+		/// <param name="exponent"></param>
+		/// <param name="modulus"></param>
+		/// <returns></returns>
+		public static BigInteger UModPow(BigInteger value, BigInteger exponent, BigInteger modulus)
+		{
+			BigInteger result = BigInteger.ModPow(value, exponent, modulus);
+			if (result < 0)
+			{
+				result += modulus;
+			}
+			return result;
+		}
+	}
 }

+ 34 - 34
CSharp/Platform/Common/Helper/ByteHelper.cs

@@ -1,35 +1,35 @@
-using System;
-using System.Collections.Generic;
-using System.Text;
-
-namespace Common.Helper
-{
-	public static class ByteHelper
-	{
-		public static string ToHex(this byte b)
-		{
-			return b.ToString("X2");
-		}
-
-		public static string ToHex(this IEnumerable<byte> bytes)
-		{
-			StringBuilder stringBuilder = new StringBuilder();
-			foreach (byte b in bytes)
-			{
-				stringBuilder.Append(b.ToString("X2"));
-			}
-			return stringBuilder.ToString();
-		}
-
-		public static string ToStr(this byte[] bytes)
-		{
-			return Encoding.Default.GetString(bytes);
-		}
-
-		public static byte[] Reverse(this byte[] bytes)
-		{
-			Array.Reverse(bytes);
-			return bytes;
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace Common.Helper
+{
+	public static class ByteHelper
+	{
+		public static string ToHex(this byte b)
+		{
+			return b.ToString("X2");
+		}
+
+		public static string ToHex(this IEnumerable<byte> bytes)
+		{
+			StringBuilder stringBuilder = new StringBuilder();
+			foreach (byte b in bytes)
+			{
+				stringBuilder.Append(b.ToString("X2"));
+			}
+			return stringBuilder.ToString();
+		}
+
+		public static string ToStr(this byte[] bytes)
+		{
+			return Encoding.Default.GetString(bytes);
+		}
+
+		public static byte[] Reverse(this byte[] bytes)
+		{
+			Array.Reverse(bytes);
+			return bytes;
+		}
+	}
 }

+ 25 - 25
CSharp/Platform/Common/Helper/EnumHelper.cs

@@ -1,26 +1,26 @@
-using System;
-
-namespace Common.Helper
-{
-	public static class EnumHelper
-	{
-		public static int EnumIndex<T>(int value)
-		{
-			int i = 0;
-			foreach (object v in Enum.GetValues(typeof (T)))
-			{
-				if ((int) v == value)
-				{
-					return i;
-				}
-				++i;
-			}
-			return -1;
-		}
-
-		public static T FromString<T>(string str)
-		{
-			return (T) Enum.Parse(typeof (T), str);
-		}
-	}
+using System;
+
+namespace Common.Helper
+{
+	public static class EnumHelper
+	{
+		public static int EnumIndex<T>(int value)
+		{
+			int i = 0;
+			foreach (object v in Enum.GetValues(typeof (T)))
+			{
+				if ((int) v == value)
+				{
+					return i;
+				}
+				++i;
+			}
+			return -1;
+		}
+
+		public static T FromString<T>(string str)
+		{
+			return (T) Enum.Parse(typeof (T), str);
+		}
+	}
 }

+ 19 - 19
CSharp/Platform/Common/Helper/LoaderHelper.cs

@@ -1,20 +1,20 @@
-using System;
-using System.IO;
-using System.Reflection;
-
-namespace Common.Helper
-{
-	public static class LoaderHelper
-	{
-		public static Assembly Load(string path)
-		{
-			if (!File.Exists(path))
-			{
-				throw new Exception($"not found path, path: {path}");
-			}
-			byte[] buffer = File.ReadAllBytes(path);
-			Assembly assembly = Assembly.Load(buffer);
-			return assembly;
-		}
-	}
+using System;
+using System.IO;
+using System.Reflection;
+
+namespace Common.Helper
+{
+	public static class LoaderHelper
+	{
+		public static Assembly Load(string path)
+		{
+			if (!File.Exists(path))
+			{
+				throw new Exception($"not found path, path: {path}");
+			}
+			byte[] buffer = File.ReadAllBytes(path);
+			Assembly assembly = Assembly.Load(buffer);
+			return assembly;
+		}
+	}
 }

+ 64 - 64
CSharp/Platform/Common/Helper/MongoHelper.cs

@@ -1,65 +1,65 @@
-using System;
-using System.IO;
-using MongoDB.Bson;
-using MongoDB.Bson.IO;
-using MongoDB.Bson.Serialization;
-
-namespace Common.Helper
-{
-	public static class MongoHelper
-	{
-		public static string ToJson(object obj)
-		{
-			return obj.ToJson();
-		}
-
-		public static string ToJson(object obj, JsonWriterSettings settings)
-		{
-			return obj.ToJson(settings);
-		}
-
-		public static T FromJson<T>(string str)
-		{
-			return BsonSerializer.Deserialize<T>(str);
-		}
-
-		public static byte[] ToBson(object obj)
-		{
-			return obj.ToBson();
-		}
-
-		public static object FromBson(Type type, byte[] bytes)
-		{
-			return BsonSerializer.Deserialize(bytes, type);
-		}
-
-		public static object FromBson(Type type, byte[] bytes, int index, int count)
-		{
-			using (MemoryStream memoryStream = new MemoryStream(bytes))
-			{
-				memoryStream.Seek(index, SeekOrigin.Begin);
-				memoryStream.Seek(index + count, SeekOrigin.End);
-				return BsonSerializer.Deserialize(memoryStream, type);
-			}
-		}
-
-		public static T FromBson<T>(byte[] bytes, int index = 0)
-		{
-			using (MemoryStream memoryStream = new MemoryStream(bytes))
-			{
-				memoryStream.Seek(index, SeekOrigin.Begin);
-				return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
-			}
-		}
-
-		public static T FromBson<T>(byte[] bytes, int index, int count)
-		{
-			using (MemoryStream memoryStream = new MemoryStream(bytes))
-			{
-				memoryStream.Seek(index, SeekOrigin.Begin);
-				memoryStream.Seek(index + count, SeekOrigin.End);
-				return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
-			}
-		}
-	}
+using System;
+using System.IO;
+using MongoDB.Bson;
+using MongoDB.Bson.IO;
+using MongoDB.Bson.Serialization;
+
+namespace Common.Helper
+{
+	public static class MongoHelper
+	{
+		public static string ToJson(object obj)
+		{
+			return obj.ToJson();
+		}
+
+		public static string ToJson(object obj, JsonWriterSettings settings)
+		{
+			return obj.ToJson(settings);
+		}
+
+		public static T FromJson<T>(string str)
+		{
+			return BsonSerializer.Deserialize<T>(str);
+		}
+
+		public static byte[] ToBson(object obj)
+		{
+			return obj.ToBson();
+		}
+
+		public static object FromBson(Type type, byte[] bytes)
+		{
+			return BsonSerializer.Deserialize(bytes, type);
+		}
+
+		public static object FromBson(Type type, byte[] bytes, int index, int count)
+		{
+			using (MemoryStream memoryStream = new MemoryStream(bytes))
+			{
+				memoryStream.Seek(index, SeekOrigin.Begin);
+				memoryStream.Seek(index + count, SeekOrigin.End);
+				return BsonSerializer.Deserialize(memoryStream, type);
+			}
+		}
+
+		public static T FromBson<T>(byte[] bytes, int index = 0)
+		{
+			using (MemoryStream memoryStream = new MemoryStream(bytes))
+			{
+				memoryStream.Seek(index, SeekOrigin.Begin);
+				return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
+			}
+		}
+
+		public static T FromBson<T>(byte[] bytes, int index, int count)
+		{
+			using (MemoryStream memoryStream = new MemoryStream(bytes))
+			{
+				memoryStream.Seek(index, SeekOrigin.Begin);
+				memoryStream.Seek(index + count, SeekOrigin.End);
+				return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
+			}
+		}
+	}
 }

+ 4 - 4
CSharp/Platform/Common/Helper/Packages.config

@@ -1,5 +1,5 @@
-<?xml version="1.0" encoding="utf-8"?>
-<packages>
-  <package id="mongocsharpdriver" version="1.9.2" targetFramework="net45" />
-  <package id="protobuf-net" version="2.0.0.668" targetFramework="net45" />
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="mongocsharpdriver" version="1.9.2" targetFramework="net45" />
+  <package id="protobuf-net" version="2.0.0.668" targetFramework="net45" />
 </packages>

+ 49 - 49
CSharp/Platform/Common/Helper/ProtobufHelper.cs

@@ -1,50 +1,50 @@
-using System.ComponentModel;
-using System.IO;
-using ProtoBuf;
-
-namespace Common.Helper
-{
-	public static class ProtobufHelper
-	{
-		public static byte[] ToBytes(object message)
-		{
-			using (MemoryStream ms = new MemoryStream())
-			{
-				Serializer.Serialize(ms, message);
-				return ms.ToArray();
-			}
-		}
-
-		public static T FromBytes<T>(byte[] bytes)
-		{
-			T t;
-			using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
-			{
-				t = Serializer.Deserialize<T>(ms);
-			}
-			ISupportInitialize iSupportInitialize = t as ISupportInitialize;
-			if (iSupportInitialize == null)
-			{
-				return t;
-			}
-			iSupportInitialize.EndInit();
-			return t;
-		}
-
-		public static T FromBytes<T>(byte[] bytes, int index, int length)
-		{
-			T t;
-			using (MemoryStream ms = new MemoryStream(bytes, index, length))
-			{
-				t = Serializer.Deserialize<T>(ms);
-			}
-			ISupportInitialize iSupportInitialize = t as ISupportInitialize;
-			if (iSupportInitialize == null)
-			{
-				return t;
-			}
-			iSupportInitialize.EndInit();
-			return t;
-		}
-	}
+using System.ComponentModel;
+using System.IO;
+using ProtoBuf;
+
+namespace Common.Helper
+{
+	public static class ProtobufHelper
+	{
+		public static byte[] ToBytes(object message)
+		{
+			using (MemoryStream ms = new MemoryStream())
+			{
+				Serializer.Serialize(ms, message);
+				return ms.ToArray();
+			}
+		}
+
+		public static T FromBytes<T>(byte[] bytes)
+		{
+			T t;
+			using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
+			{
+				t = Serializer.Deserialize<T>(ms);
+			}
+			ISupportInitialize iSupportInitialize = t as ISupportInitialize;
+			if (iSupportInitialize == null)
+			{
+				return t;
+			}
+			iSupportInitialize.EndInit();
+			return t;
+		}
+
+		public static T FromBytes<T>(byte[] bytes, int index, int length)
+		{
+			T t;
+			using (MemoryStream ms = new MemoryStream(bytes, index, length))
+			{
+				t = Serializer.Deserialize<T>(ms);
+			}
+			ISupportInitialize iSupportInitialize = t as ISupportInitialize;
+			if (iSupportInitialize == null)
+			{
+				return t;
+			}
+			iSupportInitialize.EndInit();
+			return t;
+		}
+	}
 }

+ 14 - 14
CSharp/Platform/Common/Helper/RandomHelper.cs

@@ -1,15 +1,15 @@
-using System;
-
-namespace Common.Helper
-{
-	public static class RandomHelper
-	{
-		public static UInt64 RandUInt64()
-		{
-			var bytes = new byte[8];
-			Random random = new Random();
-			random.NextBytes(bytes);
-			return BitConverter.ToUInt64(bytes, 0);
-		}
-	}
+using System;
+
+namespace Common.Helper
+{
+	public static class RandomHelper
+	{
+		public static UInt64 RandUInt64()
+		{
+			var bytes = new byte[8];
+			Random random = new Random();
+			random.NextBytes(bytes);
+			return BitConverter.ToUInt64(bytes, 0);
+		}
+	}
 }

+ 39 - 39
CSharp/Platform/Common/Helper/StringHelper.cs

@@ -1,40 +1,40 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Text;
-
-namespace Common.Helper
-{
-	public static class StringHelper
-	{
-		public static IEnumerable<byte> ToBytes(this string str)
-		{
-			byte[] byteArray = Encoding.Default.GetBytes(str);
-			return byteArray;
-		}
-
-		public static byte[] ToByteArray(this string str)
-		{
-			byte[] byteArray = Encoding.Default.GetBytes(str);
-			return byteArray;
-		}
-
-		public static byte[] HexToBytes(this string hexString)
-		{
-			if (hexString.Length % 2 != 0)
-			{
-				throw new ArgumentException($"The binary key cannot have an odd number of digits: {hexString}");
-			}
-
-			var hexAsBytes = new byte[hexString.Length / 2];
-			for (int index = 0; index < hexAsBytes.Length; index++)
-			{
-				string byteValue = "";
-				byteValue += hexString[index * 2];
-				byteValue += hexString[index * 2 + 1];
-				hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
-			}
-			return hexAsBytes;
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+
+namespace Common.Helper
+{
+	public static class StringHelper
+	{
+		public static IEnumerable<byte> ToBytes(this string str)
+		{
+			byte[] byteArray = Encoding.Default.GetBytes(str);
+			return byteArray;
+		}
+
+		public static byte[] ToByteArray(this string str)
+		{
+			byte[] byteArray = Encoding.Default.GetBytes(str);
+			return byteArray;
+		}
+
+		public static byte[] HexToBytes(this string hexString)
+		{
+			if (hexString.Length % 2 != 0)
+			{
+				throw new ArgumentException($"The binary key cannot have an odd number of digits: {hexString}");
+			}
+
+			var hexAsBytes = new byte[hexString.Length / 2];
+			for (int index = 0; index < hexAsBytes.Length; index++)
+			{
+				string byteValue = "";
+				byteValue += hexString[index * 2];
+				byteValue += hexString[index * 2 + 1];
+				hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
+			}
+			return hexAsBytes;
+		}
+	}
 }

+ 12 - 12
CSharp/Platform/Common/Helper/TimeHelper.cs

@@ -1,13 +1,13 @@
-using System;
-
-namespace Common.Helper
-{
-	public static class TimeHelper
-	{
-		public static long Now()
-		{
-			DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
-			return Convert.ToInt64((DateTime.UtcNow - epoch).TotalMilliseconds);
-		}
-	}
+using System;
+
+namespace Common.Helper
+{
+	public static class TimeHelper
+	{
+		public static long Now()
+		{
+			DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+			return Convert.ToInt64((DateTime.UtcNow - epoch).TotalMilliseconds);
+		}
+	}
 }

+ 41 - 41
CSharp/Platform/Common/Helper/XmlHelper.cs

@@ -1,42 +1,42 @@
-using System;
-using System.IO;
-using System.Text;
-using System.Xml;
-using System.Xml.Serialization;
-
-namespace Common.Helper
-{
-	public static class XmlHelper
-	{
-		/// <summary>
-		/// 对象序列化成 XML String
-		/// </summary>
-		public static string XmlSerialize<T>(T obj)
-		{
-			string xmlString = string.Empty;
-			XmlSerializer xmlSerializer = new XmlSerializer(typeof (T));
-			using (MemoryStream ms = new MemoryStream())
-			{
-				xmlSerializer.Serialize(ms, obj);
-				xmlString = Encoding.UTF8.GetString(ms.ToArray());
-			}
-			return xmlString;
-		}
-
-		/// <summary>
-		/// XML String 反序列化成对象
-		/// </summary>
-		public static T XmlDeserialize<T>(string xmlString)
-		{
-			T t = default(T);
-			XmlSerializer xmlSerializer = new XmlSerializer(typeof (T));
-			Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
-			using (XmlReader xmlReader = XmlReader.Create(xmlStream))
-			{
-				Object obj = xmlSerializer.Deserialize(xmlReader);
-				t = (T) obj;
-			}
-			return t;
-		}
-	}
+using System;
+using System.IO;
+using System.Text;
+using System.Xml;
+using System.Xml.Serialization;
+
+namespace Common.Helper
+{
+	public static class XmlHelper
+	{
+		/// <summary>
+		/// 对象序列化成 XML String
+		/// </summary>
+		public static string XmlSerialize<T>(T obj)
+		{
+			string xmlString = string.Empty;
+			XmlSerializer xmlSerializer = new XmlSerializer(typeof (T));
+			using (MemoryStream ms = new MemoryStream())
+			{
+				xmlSerializer.Serialize(ms, obj);
+				xmlString = Encoding.UTF8.GetString(ms.ToArray());
+			}
+			return xmlString;
+		}
+
+		/// <summary>
+		/// XML String 反序列化成对象
+		/// </summary>
+		public static T XmlDeserialize<T>(string xmlString)
+		{
+			T t = default(T);
+			XmlSerializer xmlSerializer = new XmlSerializer(typeof (T));
+			Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
+			using (XmlReader xmlReader = XmlReader.Create(xmlStream))
+			{
+				Object obj = xmlSerializer.Deserialize(xmlReader);
+				t = (T) obj;
+			}
+			return t;
+		}
+	}
 }

+ 21 - 21
CSharp/Platform/Common/Hooks/Native.cs

@@ -1,22 +1,22 @@
-using System;
-using System.Runtime.InteropServices;
-
-namespace Common.Hooks
-{
-	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
-			)]
-	public delegate int DRecv(IntPtr handle, IntPtr buf, int count, int flag);
-
-	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
-			)]
-	public delegate int DSend(IntPtr handle, IntPtr buf, int count, int flag);
-
-	public static class Native
-	{
-		[DllImport("Ws2_32.dll", EntryPoint = "recv")]
-		public static extern int Recv(IntPtr handle, IntPtr buf, int count, int flag);
-
-		[DllImport("Ws2_32.dll", EntryPoint = "send")]
-		public static extern int Send(IntPtr handle, IntPtr buf, int count, int flag);
-	}
+using System;
+using System.Runtime.InteropServices;
+
+namespace Common.Hooks
+{
+	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
+			)]
+	public delegate int DRecv(IntPtr handle, IntPtr buf, int count, int flag);
+
+	[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true
+			)]
+	public delegate int DSend(IntPtr handle, IntPtr buf, int count, int flag);
+
+	public static class Native
+	{
+		[DllImport("Ws2_32.dll", EntryPoint = "recv")]
+		public static extern int Recv(IntPtr handle, IntPtr buf, int count, int flag);
+
+		[DllImport("Ws2_32.dll", EntryPoint = "send")]
+		public static extern int Send(IntPtr handle, IntPtr buf, int count, int flag);
+	}
 }

+ 39 - 39
CSharp/Platform/Common/Logger/ALogDecorater.cs

@@ -1,40 +1,40 @@
-namespace Common.Logger
-{
-	public abstract class ALogDecorater
-	{
-		protected const string SEP = " ";
-		private int level;
-		protected readonly ALogDecorater decorater;
-
-		protected ALogDecorater(ALogDecorater decorater = null)
-		{
-			this.decorater = decorater;
-			this.Level = 0;
-		}
-
-		protected int Level
-		{
-			get
-			{
-				return this.level;
-			}
-			set
-			{
-				this.level = value;
-				if (this.decorater != null)
-				{
-					this.decorater.Level = value + 1;
-				}
-			}
-		}
-
-		public virtual string Decorate(string message)
-		{
-			if (this.decorater == null)
-			{
-				return message;
-			}
-			return this.decorater.Decorate(message);
-		}
-	}
+namespace Common.Logger
+{
+	public abstract class ALogDecorater
+	{
+		protected const string SEP = " ";
+		private int level;
+		protected readonly ALogDecorater decorater;
+
+		protected ALogDecorater(ALogDecorater decorater = null)
+		{
+			this.decorater = decorater;
+			this.Level = 0;
+		}
+
+		protected int Level
+		{
+			get
+			{
+				return this.level;
+			}
+			set
+			{
+				this.level = value;
+				if (this.decorater != null)
+				{
+					this.decorater.Level = value + 1;
+				}
+			}
+		}
+
+		public virtual string Decorate(string message)
+		{
+			if (this.decorater == null)
+			{
+				return message;
+			}
+			return this.decorater.Decorate(message);
+		}
+	}
 }

+ 7 - 7
CSharp/Platform/Common/Logger/ILog.cs

@@ -1,8 +1,8 @@
-namespace Common.Logger
-{
-	public interface ILog
-	{
-		void Trace(string message);
-		void Debug(string message);
-	}
+namespace Common.Logger
+{
+	public interface ILog
+	{
+		void Trace(string message);
+		void Debug(string message);
+	}
 }

+ 34 - 34
CSharp/Platform/Common/Logger/Log.cs

@@ -1,35 +1,35 @@
-namespace Common.Logger
-{
-	public static class Log
-	{
-		private static readonly ILog globalLog = new NLogAdapter(new StackInfoDecorater());
-
-		public static ILog GlobalLog
-		{
-			get
-			{
-				return globalLog;
-			}
-		}
-
-		public static void Trace(string message)
-		{
-			GlobalLog.Trace(message);
-		}
-
-		public static void Trace(string format, params object[] args)
-		{
-			GlobalLog.Trace(string.Format(format, args));
-		}
-
-		public static void Debug(string format)
-		{
-			GlobalLog.Debug(format);
-		}
-
-		public static void Debug(string format, params object[] args)
-		{
-			GlobalLog.Debug(string.Format(format, args));
-		}
-	}
+namespace Common.Logger
+{
+	public static class Log
+	{
+		private static readonly ILog globalLog = new NLogAdapter(new StackInfoDecorater());
+
+		public static ILog GlobalLog
+		{
+			get
+			{
+				return globalLog;
+			}
+		}
+
+		public static void Trace(string message)
+		{
+			GlobalLog.Trace(message);
+		}
+
+		public static void Trace(string format, params object[] args)
+		{
+			GlobalLog.Trace(string.Format(format, args));
+		}
+
+		public static void Debug(string format)
+		{
+			GlobalLog.Debug(format);
+		}
+
+		public static void Debug(string format, params object[] args)
+		{
+			GlobalLog.Debug(string.Format(format, args));
+		}
+	}
 }

+ 22 - 22
CSharp/Platform/Common/Logger/NLogAdapter.cs

@@ -1,23 +1,23 @@
-using NLog;
-
-namespace Common.Logger
-{
-	public class NLogAdapter: ALogDecorater, ILog
-	{
-		private readonly NLog.Logger logger = LogManager.GetCurrentClassLogger();
-
-		public NLogAdapter(ALogDecorater decorater = null): base(decorater)
-		{
-		}
-
-		public void Trace(string message)
-		{
-			this.logger.Trace(this.Decorate(SEP + message));
-		}
-
-		public void Debug(string message)
-		{
-			this.logger.Debug(this.Decorate(SEP + message));
-		}
-	}
+using NLog;
+
+namespace Common.Logger
+{
+	public class NLogAdapter: ALogDecorater, ILog
+	{
+		private readonly NLog.Logger logger = LogManager.GetCurrentClassLogger();
+
+		public NLogAdapter(ALogDecorater decorater = null): base(decorater)
+		{
+		}
+
+		public void Trace(string message)
+		{
+			this.logger.Trace(this.Decorate(SEP + message));
+		}
+
+		public void Debug(string message)
+		{
+			this.logger.Debug(this.Decorate(SEP + message));
+		}
+	}
 }

+ 46 - 46
CSharp/Platform/Common/Logger/StackInfoDecorater.cs

@@ -1,47 +1,47 @@
-using System.Diagnostics;
-using System.IO;
-
-namespace Common.Logger
-{
-	internal class StackInfoDecorater: ALogDecorater
-	{
-		public StackInfoDecorater(ALogDecorater decorater = null): base(decorater)
-		{
-			this.FileName = true;
-			this.FileLineNumber = true;
-		}
-
-		public bool FileName { get; set; }
-
-		public bool FileLineNumber { get; set; }
-
-		public override string Decorate(string message)
-		{
-			if (this.decorater != null)
-			{
-				message = this.decorater.Decorate(message);
-			}
-
-			if (!this.FileLineNumber && !this.FileName)
-			{
-				return message;
-			}
-
-			string extraInfo = "";
-			StackTrace stackTrace = new StackTrace(true);
-			StackFrame frame = stackTrace.GetFrame(this.Level + 3);
-
-			if (this.FileName)
-			{
-				string fileName = Path.GetFileName(frame.GetFileName());
-				extraInfo += fileName + " ";
-			}
-			if (this.FileLineNumber)
-			{
-				int fileLineNumber = frame.GetFileLineNumber();
-				extraInfo += fileLineNumber + " ";
-			}
-			return extraInfo + message;
-		}
-	}
+using System.Diagnostics;
+using System.IO;
+
+namespace Common.Logger
+{
+	internal class StackInfoDecorater: ALogDecorater
+	{
+		public StackInfoDecorater(ALogDecorater decorater = null): base(decorater)
+		{
+			this.FileName = true;
+			this.FileLineNumber = true;
+		}
+
+		public bool FileName { get; set; }
+
+		public bool FileLineNumber { get; set; }
+
+		public override string Decorate(string message)
+		{
+			if (this.decorater != null)
+			{
+				message = this.decorater.Decorate(message);
+			}
+
+			if (!this.FileLineNumber && !this.FileName)
+			{
+				return message;
+			}
+
+			string extraInfo = "";
+			StackTrace stackTrace = new StackTrace(true);
+			StackFrame frame = stackTrace.GetFrame(this.Level + 3);
+
+			if (this.FileName)
+			{
+				string fileName = Path.GetFileName(frame.GetFileName());
+				extraInfo += fileName + " ";
+			}
+			if (this.FileLineNumber)
+			{
+				int fileLineNumber = frame.GetFileLineNumber();
+				extraInfo += fileLineNumber + " ";
+			}
+			return extraInfo + message;
+		}
+	}
 }

+ 60 - 60
CSharp/Platform/Common/Network/AChannel.cs

@@ -1,61 +1,61 @@
-using System;
-using System.Collections.Generic;
-using System.Threading.Tasks;
-using Common.Base;
-
-namespace Common.Network
-{
-	[Flags]
-	public enum PacketFlags
-	{
-		None = 0,
-		Reliable = 1 << 0,
-		Unsequenced = 1 << 1,
-		NoAllocate = 1 << 2
-	}
-
-	public abstract class AChannel: Entity<AChannel>, IDisposable
-	{
-		protected IService service;
-		protected Action<AChannel> onDispose = channel => { };
-
-		protected AChannel(IService service)
-		{
-			this.service = service;
-		}
-
-		public abstract Task<bool> ConnectAsync();
-
-		/// <summary>
-		/// 发送消息
-		/// </summary>
-		public abstract void SendAsync(
-				byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
-
-		public abstract void SendAsync(
-				List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
-
-		/// <summary>
-		/// 接收消息
-		/// </summary>
-		public abstract Task<byte[]> RecvAsync();
-
-		public abstract Task<bool> DisconnnectAsync();
-
-		public abstract string RemoteAddress { get; }
-
-		public event Action<AChannel> OnDispose
-		{
-			add
-			{
-				this.onDispose += value;
-			}
-			remove
-			{
-				this.onDispose -= value;
-			}
-		}
-
-		public abstract void Dispose();
-	}
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Common.Base;
+
+namespace Common.Network
+{
+	[Flags]
+	public enum PacketFlags
+	{
+		None = 0,
+		Reliable = 1 << 0,
+		Unsequenced = 1 << 1,
+		NoAllocate = 1 << 2
+	}
+
+	public abstract class AChannel: Entity<AChannel>, IDisposable
+	{
+		protected IService service;
+		protected Action<AChannel> onDispose = channel => { };
+
+		protected AChannel(IService service)
+		{
+			this.service = service;
+		}
+
+		public abstract Task<bool> ConnectAsync();
+
+		/// <summary>
+		/// 发送消息
+		/// </summary>
+		public abstract void SendAsync(
+				byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
+
+		public abstract void SendAsync(
+				List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable);
+
+		/// <summary>
+		/// 接收消息
+		/// </summary>
+		public abstract Task<byte[]> RecvAsync();
+
+		public abstract Task<bool> DisconnnectAsync();
+
+		public abstract string RemoteAddress { get; }
+
+		public event Action<AChannel> OnDispose
+		{
+			add
+			{
+				this.onDispose += value;
+			}
+			remove
+			{
+				this.onDispose -= value;
+			}
+		}
+
+		public abstract void Dispose();
+	}
 }

+ 35 - 35
CSharp/Platform/Common/Network/IService.cs

@@ -1,36 +1,36 @@
-using System;
-using System.Threading.Tasks;
-using Common.Base;
-using MongoDB.Bson;
-
-namespace Common.Network
-{
-	public enum NetworkProtocol
-	{
-		TCP,
-		UDP,
-	}
-
-	public interface IService: IDisposable
-	{
-		/// <summary>
-		/// 将函数调用加入IService线程
-		/// </summary>
-		/// <param name="action"></param>
-		void Add(Action action);
-
-		AChannel GetChannel(ObjectId id);
-
-		AChannel GetChannel(string host, int port);
-
-		AChannel GetChannel(string address);
-
-		Task<AChannel> GetChannel();
-
-		void Remove(AChannel channel);
-
-		void Update();
-
-		TimerManager Timer { get; }
-	}
+using System;
+using System.Threading.Tasks;
+using Common.Base;
+using MongoDB.Bson;
+
+namespace Common.Network
+{
+	public enum NetworkProtocol
+	{
+		TCP,
+		UDP,
+	}
+
+	public interface IService: IDisposable
+	{
+		/// <summary>
+		/// 将函数调用加入IService线程
+		/// </summary>
+		/// <param name="action"></param>
+		void Add(Action action);
+
+		AChannel GetChannel(ObjectId id);
+
+		AChannel GetChannel(string host, int port);
+
+		AChannel GetChannel(string address);
+
+		Task<AChannel> GetChannel();
+
+		void Remove(AChannel channel);
+
+		void Update();
+
+		TimerManager Timer { get; }
+	}
 }

+ 38 - 38
CSharp/Platform/Common/Properties/AssemblyInfo.cs

@@ -1,39 +1,39 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Common")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Common")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("38372c8f-df2b-4735-9620-d997a155cd6e")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过以下
+// 特性集控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("Common")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("Common")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 使此程序集中的类型
+// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+// 则将该类型上的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("38372c8f-df2b-4735-9620-d997a155cd6e")]
+
+// 程序集的版本信息由下面四个值组成: 
+//
+//      主版本
+//      次版本 
+//      生成号
+//      修订号
+//
+// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: 
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

+ 47 - 47
CSharp/Platform/ENet/ENet.vcxproj.filters

@@ -1,48 +1,48 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <ItemGroup>
-    <ClCompile Include="callbacks.c" />
-    <ClCompile Include="compress.c" />
-    <ClCompile Include="host.c" />
-    <ClCompile Include="list.c" />
-    <ClCompile Include="packet.c" />
-    <ClCompile Include="peer.c" />
-    <ClCompile Include="protocol.c" />
-    <ClCompile Include="unix.c" />
-    <ClCompile Include="win32.c" />
-  </ItemGroup>
-  <ItemGroup>
-    <Filter Include="enet">
-      <UniqueIdentifier>{5b0e5c61-d179-4c41-a760-6154cf2db017}</UniqueIdentifier>
-    </Filter>
-  </ItemGroup>
-  <ItemGroup>
-    <ClInclude Include="enet\callbacks.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\enet.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\list.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\protocol.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\time.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\types.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\unix.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\utility.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-    <ClInclude Include="enet\win32.h">
-      <Filter>enet</Filter>
-    </ClInclude>
-  </ItemGroup>
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <ClCompile Include="callbacks.c" />
+    <ClCompile Include="compress.c" />
+    <ClCompile Include="host.c" />
+    <ClCompile Include="list.c" />
+    <ClCompile Include="packet.c" />
+    <ClCompile Include="peer.c" />
+    <ClCompile Include="protocol.c" />
+    <ClCompile Include="unix.c" />
+    <ClCompile Include="win32.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <Filter Include="enet">
+      <UniqueIdentifier>{5b0e5c61-d179-4c41-a760-6154cf2db017}</UniqueIdentifier>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClInclude Include="enet\callbacks.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\enet.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\list.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\protocol.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\time.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\types.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\unix.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\utility.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+    <ClInclude Include="enet\win32.h">
+      <Filter>enet</Filter>
+    </ClInclude>
+  </ItemGroup>
 </Project>

+ 10 - 10
CSharp/Platform/TNet/IPoller.cs

@@ -1,11 +1,11 @@
-using System;
-
-namespace TNet
-{
-	public interface IPoller
-	{
-		void Add(Action action);
-
-		void Update();
-	}
+using System;
+
+namespace TNet
+{
+	public interface IPoller
+	{
+		void Add(Action action);
+
+		void Update();
+	}
 }

+ 76 - 76
CSharp/Platform/TNet/PacketParser.cs

@@ -1,77 +1,77 @@
-using System;
-
-namespace TNet
-{
-	internal enum ParserState
-	{
-		PacketSize,
-		PacketBody,
-	}
-
-	internal class PacketParser
-	{
-		private const int packetSizeMax = 128 * 1024;
-		private readonly TBuffer buffer;
-
-		private int packetSize;
-		private readonly byte[] packetSizeBuffer = new byte[4];
-		private ParserState state;
-		private byte[] packet;
-		private bool isOK;
-
-		public PacketParser(TBuffer buffer)
-		{
-			this.buffer = buffer;
-		}
-
-		public bool Parse()
-		{
-			if (this.isOK)
-			{
-				return true;
-			}
-
-			bool finish = false;
-			while (!finish)
-			{
-				switch (this.state)
-				{
-					case ParserState.PacketSize:
-						if (this.buffer.Count < 4)
-						{
-							finish = true;
-						}
-						else
-						{
-							this.buffer.RecvFrom(this.packetSizeBuffer);
-							this.packetSize = BitConverter.ToInt32(this.packetSizeBuffer, 0);
-							this.state = ParserState.PacketBody;
-						}
-						break;
-					case ParserState.PacketBody:
-						if (this.buffer.Count < this.packetSize)
-						{
-							finish = true;
-						}
-						else
-						{
-							this.packet = new byte[this.packetSize];
-							this.buffer.RecvFrom(this.packet);
-							this.isOK = true;
-							this.state = ParserState.PacketSize;
-							finish = true;
-						}
-						break;
-				}
-			}
-			return this.isOK;
-		}
-
-		public byte[] GetPacket()
-		{
-			byte[] result = this.packet;
-			this.isOK = false;
-			return result;
-		}
-	}
+using System;
+
+namespace TNet
+{
+	internal enum ParserState
+	{
+		PacketSize,
+		PacketBody,
+	}
+
+	internal class PacketParser
+	{
+		private const int packetSizeMax = 128 * 1024;
+		private readonly TBuffer buffer;
+
+		private int packetSize;
+		private readonly byte[] packetSizeBuffer = new byte[4];
+		private ParserState state;
+		private byte[] packet;
+		private bool isOK;
+
+		public PacketParser(TBuffer buffer)
+		{
+			this.buffer = buffer;
+		}
+
+		public bool Parse()
+		{
+			if (this.isOK)
+			{
+				return true;
+			}
+
+			bool finish = false;
+			while (!finish)
+			{
+				switch (this.state)
+				{
+					case ParserState.PacketSize:
+						if (this.buffer.Count < 4)
+						{
+							finish = true;
+						}
+						else
+						{
+							this.buffer.RecvFrom(this.packetSizeBuffer);
+							this.packetSize = BitConverter.ToInt32(this.packetSizeBuffer, 0);
+							this.state = ParserState.PacketBody;
+						}
+						break;
+					case ParserState.PacketBody:
+						if (this.buffer.Count < this.packetSize)
+						{
+							finish = true;
+						}
+						else
+						{
+							this.packet = new byte[this.packetSize];
+							this.buffer.RecvFrom(this.packet);
+							this.isOK = true;
+							this.state = ParserState.PacketSize;
+							finish = true;
+						}
+						break;
+				}
+			}
+			return this.isOK;
+		}
+
+		public byte[] GetPacket()
+		{
+			byte[] result = this.packet;
+			this.isOK = false;
+			return result;
+		}
+	}
 }

+ 38 - 38
CSharp/Platform/TNet/Properties/AssemblyInfo.cs

@@ -1,39 +1,39 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("TNet")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("TNet")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("ea27beb7-2529-483e-966d-b207a76b9857")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// 有关程序集的常规信息通过以下
+// 特性集控制。更改这些特性值可修改
+// 与程序集关联的信息。
+
+[assembly: AssemblyTitle("TNet")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("Microsoft")]
+[assembly: AssemblyProduct("TNet")]
+[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// 将 ComVisible 设置为 false 使此程序集中的类型
+// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
+// 则将该类型上的 ComVisible 特性设置为 true。
+
+[assembly: ComVisible(false)]
+
+// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
+
+[assembly: Guid("ea27beb7-2529-483e-966d-b207a76b9857")]
+
+// 程序集的版本信息由下面四个值组成: 
+//
+//      主版本
+//      次版本 
+//      生成号
+//      修订号
+//
+// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
+// 方法是按如下所示使用“*”: 
+// [assembly: AssemblyVersion("1.0.*")]
+
+[assembly: AssemblyVersion("1.0.0.0")]
 [assembly: AssemblyFileVersion("1.0.0.0")]

+ 121 - 121
CSharp/Platform/TNet/TBuffer.cs

@@ -1,122 +1,122 @@
-using System;
-using System.Collections.Generic;
-
-namespace TNet
-{
-	public class TBuffer
-	{
-		public const int ChunkSize = 8096;
-
-		private readonly LinkedList<byte[]> bufferList = new LinkedList<byte[]>();
-
-		public int LastIndex { get; set; }
-
-		public int FirstIndex { get; set; }
-
-		public TBuffer()
-		{
-			this.bufferList.AddLast(new byte[ChunkSize]);
-		}
-
-		public int Count
-		{
-			get
-			{
-				if (this.bufferList.Count == 0)
-				{
-					return 0;
-				}
-				return (this.bufferList.Count - 1) * ChunkSize + this.LastIndex - this.FirstIndex;
-			}
-		}
-
-		public void AddLast()
-		{
-			this.bufferList.AddLast(new byte[ChunkSize]);
-		}
-
-		public void RemoveFirst()
-		{
-			this.bufferList.RemoveFirst();
-		}
-
-		public byte[] First
-		{
-			get
-			{
-				if (this.bufferList.First == null)
-				{
-					this.AddLast();
-				}
-				return this.bufferList.First.Value;
-			}
-		}
-
-		public byte[] Last
-		{
-			get
-			{
-				if (this.bufferList.Last == null)
-				{
-					this.AddLast();
-				}
-				return this.bufferList.Last.Value;
-			}
-		}
-
-		public void RecvFrom(byte[] buffer)
-		{
-			if (this.Count < buffer.Length || buffer.Length == 0)
-			{
-				throw new Exception($"bufferList size < n, bufferList: {this.Count} buffer length: {buffer.Length}");
-			}
-			int alreadyCopyCount = 0;
-			while (alreadyCopyCount < buffer.Length)
-			{
-				int n = buffer.Length - alreadyCopyCount;
-				if (ChunkSize - this.FirstIndex > n)
-				{
-					Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount, n);
-					this.FirstIndex += n;
-					alreadyCopyCount += n;
-				}
-				else
-				{
-					Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount,
-							ChunkSize - this.FirstIndex);
-					alreadyCopyCount += ChunkSize - this.FirstIndex;
-					this.FirstIndex = 0;
-					this.bufferList.RemoveFirst();
-				}
-			}
-		}
-
-		public void SendTo(byte[] buffer)
-		{
-			int alreadyCopyCount = 0;
-			while (alreadyCopyCount < buffer.Length)
-			{
-				if (this.LastIndex == ChunkSize)
-				{
-					this.bufferList.AddLast(new byte[ChunkSize]);
-					this.LastIndex = 0;
-				}
-
-				int n = buffer.Length - alreadyCopyCount;
-				if (ChunkSize - this.LastIndex > n)
-				{
-					Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex, n);
-					this.LastIndex += buffer.Length - alreadyCopyCount;
-					alreadyCopyCount += n;
-				}
-				else
-				{
-					Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex,
-							ChunkSize - this.LastIndex);
-					alreadyCopyCount += ChunkSize - this.LastIndex;
-					this.LastIndex = ChunkSize;
-				}
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+
+namespace TNet
+{
+	public class TBuffer
+	{
+		public const int ChunkSize = 8096;
+
+		private readonly LinkedList<byte[]> bufferList = new LinkedList<byte[]>();
+
+		public int LastIndex { get; set; }
+
+		public int FirstIndex { get; set; }
+
+		public TBuffer()
+		{
+			this.bufferList.AddLast(new byte[ChunkSize]);
+		}
+
+		public int Count
+		{
+			get
+			{
+				if (this.bufferList.Count == 0)
+				{
+					return 0;
+				}
+				return (this.bufferList.Count - 1) * ChunkSize + this.LastIndex - this.FirstIndex;
+			}
+		}
+
+		public void AddLast()
+		{
+			this.bufferList.AddLast(new byte[ChunkSize]);
+		}
+
+		public void RemoveFirst()
+		{
+			this.bufferList.RemoveFirst();
+		}
+
+		public byte[] First
+		{
+			get
+			{
+				if (this.bufferList.First == null)
+				{
+					this.AddLast();
+				}
+				return this.bufferList.First.Value;
+			}
+		}
+
+		public byte[] Last
+		{
+			get
+			{
+				if (this.bufferList.Last == null)
+				{
+					this.AddLast();
+				}
+				return this.bufferList.Last.Value;
+			}
+		}
+
+		public void RecvFrom(byte[] buffer)
+		{
+			if (this.Count < buffer.Length || buffer.Length == 0)
+			{
+				throw new Exception($"bufferList size < n, bufferList: {this.Count} buffer length: {buffer.Length}");
+			}
+			int alreadyCopyCount = 0;
+			while (alreadyCopyCount < buffer.Length)
+			{
+				int n = buffer.Length - alreadyCopyCount;
+				if (ChunkSize - this.FirstIndex > n)
+				{
+					Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount, n);
+					this.FirstIndex += n;
+					alreadyCopyCount += n;
+				}
+				else
+				{
+					Array.Copy(this.bufferList.First.Value, this.FirstIndex, buffer, alreadyCopyCount,
+							ChunkSize - this.FirstIndex);
+					alreadyCopyCount += ChunkSize - this.FirstIndex;
+					this.FirstIndex = 0;
+					this.bufferList.RemoveFirst();
+				}
+			}
+		}
+
+		public void SendTo(byte[] buffer)
+		{
+			int alreadyCopyCount = 0;
+			while (alreadyCopyCount < buffer.Length)
+			{
+				if (this.LastIndex == ChunkSize)
+				{
+					this.bufferList.AddLast(new byte[ChunkSize]);
+					this.LastIndex = 0;
+				}
+
+				int n = buffer.Length - alreadyCopyCount;
+				if (ChunkSize - this.LastIndex > n)
+				{
+					Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex, n);
+					this.LastIndex += buffer.Length - alreadyCopyCount;
+					alreadyCopyCount += n;
+				}
+				else
+				{
+					Array.Copy(buffer, alreadyCopyCount, this.bufferList.Last.Value, this.LastIndex,
+							ChunkSize - this.LastIndex);
+					alreadyCopyCount += ChunkSize - this.LastIndex;
+					this.LastIndex = ChunkSize;
+				}
+			}
+		}
+	}
 }

+ 230 - 230
CSharp/Platform/TNet/TChannel.cs

@@ -1,231 +1,231 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using Common.Helper;
-using Common.Logger;
-using Common.Network;
-using MongoDB.Bson;
-
-namespace TNet
-{
-	public class TChannel: AChannel
-	{
-		private const int SendInterval = 0;
-		private TSocket socket;
-
-		private readonly TBuffer recvBuffer = new TBuffer();
-		private readonly TBuffer sendBuffer = new TBuffer();
-
-		private ObjectId sendTimer = ObjectId.Empty;
-		private Action onParseComplete = () => { };
-		private readonly PacketParser parser;
-		private readonly string remoteAddress;
-		private bool isConnected;
-
-		public TChannel(TSocket socket, TService service): base(service)
-		{
-			this.isConnected = true;
-			this.socket = socket;
-			this.service = service;
-			this.parser = new PacketParser(this.recvBuffer);
-			this.remoteAddress = this.socket.RemoteAddress;
-			this.StartRecv();
-		}
-
-		public TChannel(TSocket socket, string host, int port, TService service): base(service)
-		{
-			this.socket = socket;
-			this.service = service;
-			this.parser = new PacketParser(this.recvBuffer);
-			this.remoteAddress = host + ":" + port;
-		}
-
-		private void Dispose(bool disposing)
-		{
-			if (this.socket == null)
-			{
-				return;
-			}
-
-			this.onDispose(this);
-
-			if (disposing)
-			{
-				// 释放托管的资源
-				this.socket.Dispose();
-			}
-
-			// 释放非托管资源
-			this.service.Remove(this);
-			this.socket = null;
-		}
-
-		~TChannel()
-		{
-			this.Dispose(false);
-		}
-
-		public override void Dispose()
-		{
-			this.Dispose(true);
-			GC.SuppressFinalize(this);
-		}
-
-		public override async Task<bool> ConnectAsync()
-		{
-			string[] ss = this.RemoteAddress.Split(':');
-			int port = int.Parse(ss[1]);
-			bool result = await this.socket.ConnectAsync(ss[0], port);
-			this.isConnected = true;
-			this.SetStartSendFlag();
-			this.StartRecv();
-			return result;
-		}
-
-		private void SetStartSendFlag()
-		{
-			if (this.sendTimer == ObjectId.Empty)
-			{
-				this.sendTimer = this.service.Timer.Add(TimeHelper.Now() + SendInterval, this.StartSend);
-			}
-		}
-
-		public override void SendAsync(
-				byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
-		{
-			byte[] size = BitConverter.GetBytes(buffer.Length);
-			this.sendBuffer.SendTo(size);
-			this.sendBuffer.SendTo(buffer);
-			if (this.isConnected)
-			{
-				this.SetStartSendFlag();
-			}
-		}
-
-		public override void SendAsync(
-				List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
-		{
-			int size = buffers.Select(b => b.Length).Sum();
-			byte[] sizeBuffer = BitConverter.GetBytes(size);
-			this.sendBuffer.SendTo(sizeBuffer);
-			foreach (byte[] buffer in buffers)
-			{
-				this.sendBuffer.SendTo(buffer);
-			}
-			if (this.isConnected)
-			{
-				this.SetStartSendFlag();
-			}
-		}
-
-		public ObjectId SendTimer
-		{
-			get
-			{
-				return this.sendTimer;
-			}
-		}
-
-		public override Task<byte[]> RecvAsync()
-		{
-			var tcs = new TaskCompletionSource<byte[]>();
-
-			if (this.parser.Parse())
-			{
-				tcs.SetResult(this.parser.GetPacket());
-			}
-			else
-			{
-				this.onParseComplete = () => this.ParseComplete(tcs);
-			}
-			return tcs.Task;
-		}
-
-		public override async Task<bool> DisconnnectAsync()
-		{
-			return await this.socket.DisconnectAsync();
-		}
-
-		public override string RemoteAddress
-		{
-			get
-			{
-				return this.remoteAddress;
-			}
-		}
-
-		private void ParseComplete(TaskCompletionSource<byte[]> tcs)
-		{
-			byte[] packet = this.parser.GetPacket();
-			this.onParseComplete = () => { };
-			tcs.SetResult(packet);
-		}
-
-		public async void StartSend()
-		{
-			try
-			{
-				while (true)
-				{
-					if (this.sendBuffer.Count == 0)
-					{
-						break;
-					}
-					int sendSize = TBuffer.ChunkSize - this.sendBuffer.FirstIndex;
-					if (sendSize > this.sendBuffer.Count)
-					{
-						sendSize = this.sendBuffer.Count;
-					}
-					int n = await this.socket.SendAsync(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
-
-					this.sendBuffer.FirstIndex += n;
-					if (this.sendBuffer.FirstIndex == TBuffer.ChunkSize)
-					{
-						this.sendBuffer.FirstIndex = 0;
-						this.sendBuffer.RemoveFirst();
-					}
-				}
-
-				this.sendTimer = ObjectId.Empty;
-			}
-			catch (Exception e)
-			{
-				Log.Debug(e.ToString());
-			}
-		}
-
-		private async void StartRecv()
-		{
-			try
-			{
-				while (true)
-				{
-					int n = await this.socket.RecvAsync(
-						this.recvBuffer.Last, this.recvBuffer.LastIndex, TBuffer.ChunkSize - this.recvBuffer.LastIndex);
-					if (n == 0)
-					{
-						break;
-					}
-
-					this.recvBuffer.LastIndex += n;
-					if (this.recvBuffer.LastIndex == TBuffer.ChunkSize)
-					{
-						this.recvBuffer.AddLast();
-						this.recvBuffer.LastIndex = 0;
-					}
-
-					// 解析封包
-					if (this.parser.Parse())
-					{
-						this.onParseComplete();
-					}
-				}
-			}
-			catch (Exception e)
-			{
-				Log.Trace(e.ToString());
-			}
-		}
-	}
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Common.Helper;
+using Common.Logger;
+using Common.Network;
+using MongoDB.Bson;
+
+namespace TNet
+{
+	public class TChannel: AChannel
+	{
+		private const int SendInterval = 0;
+		private TSocket socket;
+
+		private readonly TBuffer recvBuffer = new TBuffer();
+		private readonly TBuffer sendBuffer = new TBuffer();
+
+		private ObjectId sendTimer = ObjectId.Empty;
+		private Action onParseComplete = () => { };
+		private readonly PacketParser parser;
+		private readonly string remoteAddress;
+		private bool isConnected;
+
+		public TChannel(TSocket socket, TService service): base(service)
+		{
+			this.isConnected = true;
+			this.socket = socket;
+			this.service = service;
+			this.parser = new PacketParser(this.recvBuffer);
+			this.remoteAddress = this.socket.RemoteAddress;
+			this.StartRecv();
+		}
+
+		public TChannel(TSocket socket, string host, int port, TService service): base(service)
+		{
+			this.socket = socket;
+			this.service = service;
+			this.parser = new PacketParser(this.recvBuffer);
+			this.remoteAddress = host + ":" + port;
+		}
+
+		private void Dispose(bool disposing)
+		{
+			if (this.socket == null)
+			{
+				return;
+			}
+
+			this.onDispose(this);
+
+			if (disposing)
+			{
+				// 释放托管的资源
+				this.socket.Dispose();
+			}
+
+			// 释放非托管资源
+			this.service.Remove(this);
+			this.socket = null;
+		}
+
+		~TChannel()
+		{
+			this.Dispose(false);
+		}
+
+		public override void Dispose()
+		{
+			this.Dispose(true);
+			GC.SuppressFinalize(this);
+		}
+
+		public override async Task<bool> ConnectAsync()
+		{
+			string[] ss = this.RemoteAddress.Split(':');
+			int port = int.Parse(ss[1]);
+			bool result = await this.socket.ConnectAsync(ss[0], port);
+			this.isConnected = true;
+			this.SetStartSendFlag();
+			this.StartRecv();
+			return result;
+		}
+
+		private void SetStartSendFlag()
+		{
+			if (this.sendTimer == ObjectId.Empty)
+			{
+				this.sendTimer = this.service.Timer.Add(TimeHelper.Now() + SendInterval, this.StartSend);
+			}
+		}
+
+		public override void SendAsync(
+				byte[] buffer, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
+		{
+			byte[] size = BitConverter.GetBytes(buffer.Length);
+			this.sendBuffer.SendTo(size);
+			this.sendBuffer.SendTo(buffer);
+			if (this.isConnected)
+			{
+				this.SetStartSendFlag();
+			}
+		}
+
+		public override void SendAsync(
+				List<byte[]> buffers, byte channelID = 0, PacketFlags flags = PacketFlags.Reliable)
+		{
+			int size = buffers.Select(b => b.Length).Sum();
+			byte[] sizeBuffer = BitConverter.GetBytes(size);
+			this.sendBuffer.SendTo(sizeBuffer);
+			foreach (byte[] buffer in buffers)
+			{
+				this.sendBuffer.SendTo(buffer);
+			}
+			if (this.isConnected)
+			{
+				this.SetStartSendFlag();
+			}
+		}
+
+		public ObjectId SendTimer
+		{
+			get
+			{
+				return this.sendTimer;
+			}
+		}
+
+		public override Task<byte[]> RecvAsync()
+		{
+			var tcs = new TaskCompletionSource<byte[]>();
+
+			if (this.parser.Parse())
+			{
+				tcs.SetResult(this.parser.GetPacket());
+			}
+			else
+			{
+				this.onParseComplete = () => this.ParseComplete(tcs);
+			}
+			return tcs.Task;
+		}
+
+		public override async Task<bool> DisconnnectAsync()
+		{
+			return await this.socket.DisconnectAsync();
+		}
+
+		public override string RemoteAddress
+		{
+			get
+			{
+				return this.remoteAddress;
+			}
+		}
+
+		private void ParseComplete(TaskCompletionSource<byte[]> tcs)
+		{
+			byte[] packet = this.parser.GetPacket();
+			this.onParseComplete = () => { };
+			tcs.SetResult(packet);
+		}
+
+		public async void StartSend()
+		{
+			try
+			{
+				while (true)
+				{
+					if (this.sendBuffer.Count == 0)
+					{
+						break;
+					}
+					int sendSize = TBuffer.ChunkSize - this.sendBuffer.FirstIndex;
+					if (sendSize > this.sendBuffer.Count)
+					{
+						sendSize = this.sendBuffer.Count;
+					}
+					int n = await this.socket.SendAsync(this.sendBuffer.First, this.sendBuffer.FirstIndex, sendSize);
+
+					this.sendBuffer.FirstIndex += n;
+					if (this.sendBuffer.FirstIndex == TBuffer.ChunkSize)
+					{
+						this.sendBuffer.FirstIndex = 0;
+						this.sendBuffer.RemoveFirst();
+					}
+				}
+
+				this.sendTimer = ObjectId.Empty;
+			}
+			catch (Exception e)
+			{
+				Log.Debug(e.ToString());
+			}
+		}
+
+		private async void StartRecv()
+		{
+			try
+			{
+				while (true)
+				{
+					int n = await this.socket.RecvAsync(
+						this.recvBuffer.Last, this.recvBuffer.LastIndex, TBuffer.ChunkSize - this.recvBuffer.LastIndex);
+					if (n == 0)
+					{
+						break;
+					}
+
+					this.recvBuffer.LastIndex += n;
+					if (this.recvBuffer.LastIndex == TBuffer.ChunkSize)
+					{
+						this.recvBuffer.AddLast();
+						this.recvBuffer.LastIndex = 0;
+					}
+
+					// 解析封包
+					if (this.parser.Parse())
+					{
+						this.onParseComplete();
+					}
+				}
+			}
+			catch (Exception e)
+			{
+				Log.Trace(e.ToString());
+			}
+		}
+	}
 }

+ 64 - 64
CSharp/Platform/TNet/TNet.csproj

@@ -1,65 +1,65 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
-  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
-  <PropertyGroup>
-    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
-    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
-    <ProjectGuid>{B1B78524-3F75-40D7-BF12-10B25A00C590}</ProjectGuid>
-    <OutputType>Library</OutputType>
-    <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>TNet</RootNamespace>
-    <AssemblyName>TNet</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
-    <FileAlignment>512</FileAlignment>
-    <TargetFrameworkProfile />
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
-    <DebugSymbols>true</DebugSymbols>
-    <DebugType>full</DebugType>
-    <Optimize>false</Optimize>
-    <OutputPath>..\..\Bin\Debug\</OutputPath>
-    <DefineConstants>DEBUG;TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
-    <DebugType>pdbonly</DebugType>
-    <Optimize>true</Optimize>
-    <OutputPath>..\..\Bin\Release\</OutputPath>
-    <DefineConstants>TRACE</DefineConstants>
-    <ErrorReport>prompt</ErrorReport>
-    <WarningLevel>4</WarningLevel>
-  </PropertyGroup>
-  <ItemGroup>
-    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
-      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
-      <Private>True</Private>
-    </Reference>
-    <Reference Include="System" />
-    <Reference Include="System.Core" />
-  </ItemGroup>
-  <ItemGroup>
-    <Compile Include="IPoller.cs" />
-    <Compile Include="PacketParser.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
-    <Compile Include="TBuffer.cs" />
-    <Compile Include="TChannel.cs" />
-    <Compile Include="TPoller.cs" />
-    <Compile Include="TService.cs" />
-    <Compile Include="TSocket.cs" />
-  </ItemGroup>
-  <ItemGroup>
-    <ProjectReference Include="..\Common\Common.csproj">
-      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
-      <Name>Common</Name>
-    </ProjectReference>
-  </ItemGroup>
-  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
-  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
-       Other similar extension points exist, see Microsoft.Common.targets.
-  <Target Name="BeforeBuild">
-  </Target>
-  <Target Name="AfterBuild">
-  </Target>
-  -->
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{B1B78524-3F75-40D7-BF12-10B25A00C590}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>TNet</RootNamespace>
+    <AssemblyName>TNet</AssemblyName>
+    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="MongoDB.Bson, Version=2.0.1.27, Culture=neutral, processorArchitecture=MSIL">
+      <HintPath>..\..\packages\MongoDB.Bson.2.0.1\lib\net45\MongoDB.Bson.dll</HintPath>
+      <Private>True</Private>
+    </Reference>
+    <Reference Include="System" />
+    <Reference Include="System.Core" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="IPoller.cs" />
+    <Compile Include="PacketParser.cs" />
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="TBuffer.cs" />
+    <Compile Include="TChannel.cs" />
+    <Compile Include="TPoller.cs" />
+    <Compile Include="TService.cs" />
+    <Compile Include="TSocket.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\Common\Common.csproj">
+      <Project>{F06B995E-6508-4C5C-A396-554316C9215D}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
 </Project>

+ 37 - 37
CSharp/Platform/TNet/TPoller.cs

@@ -1,38 +1,38 @@
-using System;
-using System.Collections.Concurrent;
-using System.Collections.Generic;
-
-namespace TNet
-{
-	public class TPoller: IPoller
-	{
-		// 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
-		private readonly ConcurrentQueue<Action> concurrentQueue = new ConcurrentQueue<Action>();
-
-		private readonly Queue<Action> localQueue = new Queue<Action>();
-
-		public void Add(Action action)
-		{
-			this.concurrentQueue.Enqueue(action);
-		}
-
-		public void Update()
-		{
-			while (true)
-			{
-				Action action;
-				if (!this.concurrentQueue.TryDequeue(out action))
-				{
-					break;
-				}
-				this.localQueue.Enqueue(action);
-			}
-
-			while (this.localQueue.Count > 0)
-			{
-				Action a = this.localQueue.Dequeue();
-				a();
-			}
-		}
-	}
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+
+namespace TNet
+{
+	public class TPoller: IPoller
+	{
+		// 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
+		private readonly ConcurrentQueue<Action> concurrentQueue = new ConcurrentQueue<Action>();
+
+		private readonly Queue<Action> localQueue = new Queue<Action>();
+
+		public void Add(Action action)
+		{
+			this.concurrentQueue.Enqueue(action);
+		}
+
+		public void Update()
+		{
+			while (true)
+			{
+				Action action;
+				if (!this.concurrentQueue.TryDequeue(out action))
+				{
+					break;
+				}
+				this.localQueue.Enqueue(action);
+			}
+
+			while (this.localQueue.Count > 0)
+			{
+				Action a = this.localQueue.Dequeue();
+				a();
+			}
+		}
+	}
 }

Некоторые файлы не были показаны из-за большого количества измененных файлов