From 628d770c1890bf3292ff0d70470916c9c437a7ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=A5=E6=B1=9D=E6=A3=8B=E8=8C=97?= <505554090@qq.com> Date: Fri, 18 Aug 2023 23:39:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BC=81=E4=B8=9A=E7=89=88?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PerformanceTest.sln | 30 - .../RpcPerformanceConsoleApp/BeetleXRpc.cs | 0 .../RpcPerformanceConsoleApp/NewLifeRpc.cs | 0 .../RpcPerformanceConsoleApp/Program.cs | 0 .../RpcPerformanceConsoleApp.csproj | 2 +- .../RpcPerformanceConsoleApp/TestController.cs | 18 +- .../RpcPerformanceConsoleApp/TouchSocketRpc.cs | 46 +- performancetest/Rpc/RpcPerformanceTest.sln | 25 + src/Directory.Build.props | 40 + src/Keys/TouchSocket.snk | Bin 0 -> 596 bytes .../Smtp/Components/WebsocketSmtpService.cs | 26 +- .../Components/WebsocketSmtpSocketClient.cs | 20 +- .../ApplicationBuilderExtensions.cs | 4 +- .../WebsocketSmtpServiceExtensions.cs | 10 +- .../Smtp/Interfaces/IWebsocketSmtpService.cs | 8 +- .../Interfaces/IWebsocketSmtpSocketClient.cs | 7 +- .../Middlewares/WebsocketSmtpMiddleware.cs | 18 +- .../SocketsServiceCollectionExtensions.cs | 80 +- .../TouchSocket.AspNetCore.csproj | 63 +- .../TouchSocket.CodeAnalyzer.csproj | 35 +- .../Common/AspNetCoreContainer.cs | 8 +- ...ouchSocket.Core.DependencyInjection.csproj | 47 +- src/TouchSocket.Core/Args/MsgEventArgs.cs | 10 +- .../Common/Enum/ResultCode.cs | 2 +- src/TouchSocket.Core/Common/Metadata.cs | 27 +- .../Common/MetadataFastBinaryConverter.cs | 2 +- src/TouchSocket.Core/Data/MD5.cs | 21 + .../Dependency/ContainerExtension.cs | 2 +- .../Dependency/DependencyObject.cs | 2 - .../Dependency/DependencyProperty.cs | 2 +- src/TouchSocket.Core/Dependency/IContainer.cs | 2 +- .../Dependency/IDependencyObject.cs | 4 - .../Dependency/IDependencyProperty.cs | 8 +- .../Extensions/BytesExtension.cs | 8 + .../Extensions/RangeExtension.cs | 10 +- src/TouchSocket.Core/Flow/Counter.cs | 4 +- src/TouchSocket.Core/Flow/FlowGate.cs | 4 +- src/TouchSocket.Core/IO/ConsoleAction.cs | 104 +-- src/TouchSocket.Core/IO/FileIO/FilePool.cs | 5 +- src/TouchSocket.Core/Logger/FileLogger.cs | 10 +- src/TouchSocket.Core/Logger/LoggerBase.cs | 4 +- .../Logger/LoggerExtensions.cs | 2 +- src/TouchSocket.Core/Packages_/IPackage.cs | 4 +- src/TouchSocket.Core/Packages_/MsgPackage.cs | 4 +- .../Packages_/MsgRouterPackage.cs | 4 +- src/TouchSocket.Core/Packages_/PackageBase.cs | 8 +- .../Packages_/RouterPackage.cs | 12 +- src/TouchSocket.Core/Packages_/WaitPackage.cs | 4 +- .../Packages_/WaitRouterPackage.cs | 45 +- src/TouchSocket.Core/Plugins/PluginModel.cs | 2 - .../Plugins/PluginsManager.cs | 16 +- .../Plugins/PluginsManagerExtension.cs | 4 +- src/TouchSocket.Core/Pool/ArrayPool.cs | 22 +- .../Pool/ByteManager/ByteBlock.cs | 3 +- .../Pool/ByteManager/BytePool.cs | 15 +- .../Reflection/DynamicMethodMemberAccessor.cs | 8 +- .../Reflection/InstanceCreater.cs | 4 - .../Reflection/MemberAccessor.cs | 2 +- src/TouchSocket.Core/Reflection/Method.cs | 283 +++---- src/TouchSocket.Core/Run/Action/EasyTask.cs | 5 +- .../FastBinary/FastBinaryFormatter.cs | 30 +- .../Serialization/SerializeConvert.cs | 14 +- src/TouchSocket.Core/TouchSocket.Core.csproj | 45 +- src/TouchSocket.Core/WaitPool/IWaitData.cs | 4 - src/TouchSocket.Core/WaitPool/WaitData.cs | 13 +- .../WaitPool/WaitDataAsync.cs | 18 +- .../WaitPool/WaitHandlePool.cs | 2 +- src/TouchSocket.Dmtp/Actor/DmtpActor.cs | 21 +- src/TouchSocket.Dmtp/Actor/IDmtpActor.cs | 5 + .../Channel/ChannelPackage.cs | 7 +- .../Channel/DmtpChannelExtension.cs | 6 +- .../Channel/IDmtpChannelAsync.cs | 6 +- .../Channel/InternalChannelAsync.cs | 6 +- .../Channel/WaitCreateChannelPackage.cs | 4 +- .../Components/Http/HttpDmtpClient.cs | 4 +- .../Components/Http/HttpDmtpService.cs | 1 - .../Components/Http/HttpDmtpSocketClient.cs | 2 +- .../Http/Interface/IHttpDmtpService.cs | 1 - .../Http/Interface/IHttpDmtpSocketClient.cs | 4 +- .../TCP/Interface/ITcpDmtpService.cs | 2 +- .../TCP/Interface/ITcpDmtpSocketClient.cs | 4 +- .../Interface/IWebsocketDmtpClient.cs | 4 +- .../Interface/IWebsocketDmtpClientBase.cs | 4 +- .../Websocket/WebsocketDmtpClient.cs | 20 +- src/TouchSocket.Dmtp/Enum/RouteType.cs | 2 +- .../EventArgs/DmtpVerifyEventArgs.cs | 1 - .../Extensions/DmtpActorExtension.cs | 14 +- .../Extensions/DmtpConfigExtension.cs | 54 +- .../Extensions/DmtpFeatureExtension.cs | 10 +- .../Extensions/DmtpPluginsManagerExtension.cs | 20 +- .../Actor/DmtpFileTransferActor.cs | 130 ++-- .../Actor/IDmtpFileTransferActor.cs | 15 +- .../FileTransfer/Common/FileResourceInfo.cs | 4 +- .../Common/FileResourceLocator.cs | 41 +- .../FileTransfer/Common/FileSection.cs | 4 +- .../FileTransfer/Common/FileSectionResult.cs | 21 +- .../FileTransfer/Common/FileSectionStatus.cs | 1 - .../FileTransfer/Common/RemoteFileInfo.cs | 4 +- .../Common/RemoteFileSystemInfo.cs | 4 +- .../FileTransfer/Common/TouchRpcFileInfo.cs | 4 +- .../Common/WaitFileInfoPackage.cs | 11 +- .../FileTransfer/Common/WaitFileResource.cs | 6 +- .../FileTransfer/Common/WaitFileSection.cs | 4 +- .../Common/WaitFinishedPackage.cs | 4 +- .../Common/WaitSmallFilePackage.cs | 5 +- .../DmtpFileTransferActorExtension.cs | 5 - .../FileTransfer/DmtpFileTransferFeature.cs | 30 +- .../FileTransfer/Enum/TransferType.cs} | 29 +- .../EventArgs/FileOperationEventArgs.cs | 119 --- .../EventArgs/FileTransferStatusEventArgs.cs | 64 -- .../EventArgs/FileTransferedEventArgs.cs} | 37 +- .../EventArgs/FileTransferingEventArgs.cs} | 85 +-- .../Extensions/TransferTypeExtension.cs | 18 + .../Plugins/IDmtpFileTransferedPlugin.cs | 12 +- .../Plugins/IDmtpFileTransferingPlugin.cs | 6 +- .../Services/IFileResourceController.cs | 2 +- .../Features/Redis/RedisFeature.cs | 2 +- .../Features/Redis/RedisRequestWaitPackage.cs | 4 +- .../Redis/RedisResponseWaitPackage.cs | 4 +- .../Features/Rpc/Actor/DmtpRpcActor.cs | 446 +++++++++-- ...tDmtpRpcActor.cs => TargetDmtpRpcActor.cs} | 6 +- .../Features/Rpc/CanceledPackage.cs | 4 +- .../Features/Rpc/DmtpRpcActorExtension.cs | 9 +- .../Features/Rpc/DmtpRpcPackage.cs | 7 +- .../Interfaces/IDmtpActorObject.cs | 4 +- .../Interfaces/IDmtpFeature.cs | 8 +- .../Plugins/DmtpHeartbeatPlugin.cs | 40 +- .../Plugins/IDmtpCreateChannelPlugin.cs | 6 +- .../Plugins/IDmtpHandshakedPlugin.cs | 14 +- .../Plugins/IDmtpHandshakingPlugin.cs | 8 +- .../Plugins/IDmtpRoutingPlugin.cs | 8 +- .../ProtocolSecure/IProtocolSecureService.cs | 8 +- .../ProtocolSecure/ProtocolSecureService.cs | 17 +- .../Resources/TouchSocketDmtpStatus.cs | 11 +- .../Services/Route/DmtpRouteService.cs | 5 - .../Route/DmtpRouteServiceExtension.cs | 3 +- .../Services/Route/IDmtpRouteService.cs | 4 - src/TouchSocket.Dmtp/TouchSocket.Dmtp.csproj | 50 +- src/TouchSocket.Http/Common/HttpBase.cs | 18 +- src/TouchSocket.Http/Common/HttpMethod.cs | 11 +- src/TouchSocket.Http/Common/HttpRequest.cs | 39 +- src/TouchSocket.Http/Common/HttpResponse.cs | 11 +- .../Common/Internal/InternalHttpHeader.cs | 7 +- .../Common/Internal/InternalHttpParams.cs | 64 ++ src/TouchSocket.Http/Components/HttpClient.cs | 128 ++-- .../Components/HttpClientSlim.cs | 142 ++++ .../Interfaces}/IHttpClient.cs | 14 - .../Components/Interfaces/IHttpClientBase.cs | 11 + .../Interfaces}/IHttpService.cs | 0 .../Interfaces/IHttpSocketClient.cs | 11 + .../HttpClientDataHandlingAdapter.cs | 8 +- .../Extensions/HttpExtensions.cs | 11 +- .../Extensions/HttpPluginsManagerExtension.cs | 10 + src/TouchSocket.Http/Interface/IHttpHeader.cs | 14 +- src/TouchSocket.Http/Interface/IHttpParams.cs | 17 + .../Plugins/Interfaces/IHttpDeletePlugin.cs | 15 +- .../Plugins/Interfaces/IHttpGetPlugin.cs | 15 +- .../Plugins/Interfaces/IHttpPlugin.cs | 5 +- .../Plugins/Interfaces/IHttpPostPlugin.cs | 15 +- .../Plugins/Interfaces/IHttpPutPlugin.cs | 15 +- src/TouchSocket.Http/TouchSocket.Http.csproj | 52 +- .../WebSockets/Common/WSTools.cs | 2 +- .../WebSockets/Components/WebSocketClient.cs | 61 +- ...nsions.cs => WebSocketClientExtensions.cs} | 4 +- ...ons.cs => WebSocketDataFrameExtensions.cs} | 2 +- .../Extensions/WebSocketExtension.cs | 142 ---- .../WebSocketPluginsManagerExtension.cs | 5 +- .../Extensions/WebSocketServerExtensions.cs | 6 +- .../Interfaces/IWebsocketClosingPlugin.cs | 20 +- .../Interfaces/IWebsocketHandshakedPlugin.cs | 20 +- .../Interfaces/IWebsocketHandshakingPlugin.cs | 20 +- .../Interfaces/IWebsocketReceivedPlugin.cs | 20 +- ...lugin.cs => WebSocketCommandLinePlugin.cs} | 10 +- .../WebSockets/Plugins/WebSocketFeature.cs | 4 +- .../Plugins/WebSocketHeartbeatPlugin.cs | 39 +- .../Common/HttpJsonRpcCallContext.cs | 30 + .../Common/JsonResponseContext.cs | 33 +- ...llContext.cs => JsonRpcCallContextBase.cs} | 35 +- .../Common/JsonRpcContext.cs | 8 +- .../Common/JsonRpcError.cs | 27 + .../Common/JsonRpcRequest.cs | 14 +- .../Common/JsonRpcResponse.cs | 2 +- .../Common/JsonRpcUtility.cs | 11 +- .../Common/JsonRpcWaitResult.cs | 4 +- .../Common/TcpJsonRpcCallContext.cs | 23 + .../Common/WebSocketJsonRpcCallContext.cs | 15 + .../Components/HttpJsonRpcClient.cs | 345 +++++++++ .../Components/HttpJsonRpcClientSlim.cs | 322 ++++++++ .../Components/JsonRpcClient.cs | 712 ------------------ .../Components/TcpJsonRpcClient.cs | 321 ++++++++ .../Components/WebSocketJsonRpcClient.cs | 288 +++++++ .../Config/JsonRpcConfigExtensions.cs | 64 -- .../Extensions/HttpSocketClientExtension.cs | 38 + .../Extensions/JsonRpcConfigExtension.cs | 86 +++ .../JsonRpcPluginsManagerExtension.cs | 26 +- .../Interface/IHttpJsonRpcCallContext.cs | 15 + .../Interface/IHttpJsonRpcClient.cs | 16 + .../Interface/IHttpJsonRpcClientSlim.cs | 15 + .../Interface/IJsonRpcCallContext.cs | 8 +- .../Interface/IJsonRpcClient.cs | 2 +- .../Interface/IJsonRpcRequestInfo.cs | 1 - .../Interface/ITcpJsonRpcCallContext.cs | 15 + .../Interface/ITcpJsonRpcClient.cs | 13 + .../Interface/IWebSocketJsonRpcClient.cs | 16 + .../Plugins/HttpJsonRpcParserPlugin.cs | 91 +++ ...erPlugin.cs => JsonRpcParserPluginBase.cs} | 401 ++++------ .../Plugins/TcpJsonRpcParserPlugin.cs | 103 +++ .../Plugins/WebSocketJsonRpcParserPlugin.cs | 98 +++ .../Resources/TouchSocketJsonRpcResource.cs | 4 +- .../TouchSocket.JsonRpc.csproj | 55 +- .../Attribute/GeneratorRpcMethodAttribute.cs | 1 - .../Attribute/GeneratorRpcProxyAttribute.cs | 1 - src/TouchSocket.Rpc/Code/CodeGenerator.cs | 1 - src/TouchSocket.Rpc/Common/ActionMap.cs | 2 +- src/TouchSocket.Rpc/Common/InvokeOption.cs | 8 +- .../Extensions/RpcParserExtension.cs | 7 +- .../Extensions/RpcPluginsManagerExtension.cs | 6 +- src/TouchSocket.Rpc/Interface/IRpcClient.cs | 2 +- .../Interface/ITargetRpcClient.cs | 5 +- .../Resources/TouchSocketRpcResource.cs | 2 - src/TouchSocket.Rpc/TouchSocket.Rpc.csproj | 46 +- .../LICENSE.txt | 201 +++++ .../TouchSocket.SourceGenerator.Rpc.csproj | 4 +- src/TouchSocket.SourceGenerator.Rpc/logo.ico | Bin 0 -> 16958 bytes src/TouchSocket.SourceGenerator.Rpc/logo.png | Bin 0 -> 11413 bytes .../Attribute/WebApiAttribute.cs | 14 +- .../Components/WebApiClient.cs | 40 +- .../Components/WebApiClientSlim.cs | 328 ++++++++ .../EventArgs/WebApiEventArgs.cs | 66 ++ .../Interface/IWebApiClient.cs | 3 +- .../Interface/IWebApiClientBase.cs | 11 + .../Plugins/Interfaces/IWebApiPlugin.cs | 35 + .../Plugins/WebApiParserPlugin.cs | 13 +- .../Resources/TouchSocketWebApiResource.cs | 4 +- .../TouchSocket.WebApi.csproj | 48 +- .../Components/XmlRpcClient.cs | 4 +- .../Plugins/XmlRpcParserPlugin.cs | 3 +- .../Resources/TouchSocketXmlRpcResource.cs | 4 +- .../TouchSocket.XmlRpc.csproj | 50 +- TouchSocket.sln => src/TouchSocket.sln | 29 +- src/TouchSocket/Common/DelaySender.cs | 11 +- src/TouchSocket/Common/IPHost.cs | 5 +- .../Common/Options/DelaySenderOption.cs | 8 +- src/TouchSocket/Common/Protocol.cs | 2 +- src/TouchSocket/Common/TouchSocketUtility.cs | 8 +- .../Components/Tcp/SocketClient.cs | 53 +- src/TouchSocket/Components/Tcp/TcpClient.cs | 133 ++-- src/TouchSocket/Components/Tcp/TcpService.cs | 16 +- src/TouchSocket/Components/Udp/UdpSession.cs | 18 +- ...CustomBigFixedHeaderDataHandlingAdapter.cs | 2 +- ...FixedHeaderByteBlockDataHandlingAdapter.cs | 2 +- .../DataAdapter/Test/TcpDataAdapterTester.cs | 1 - .../DataAdapter/Test/UdpDataAdapterTester.cs | 2 - .../EventArgs/ConnectedEventArgs.cs | 9 +- .../EventArgs/DisconnectEventArgs.cs | 1 - .../EventArgs/IdChangedEventArgs.cs | 2 +- .../DataHandlingAdapterExtension.cs | 6 +- .../SocketPluginsManagerExtension.cs | 1 - .../Extensions/TouchSocketConfigExtension.cs | 9 +- src/TouchSocket/Interface/IClient.cs | 2 +- src/TouchSocket/Interface/ISocketClient.cs | 8 + src/TouchSocket/Plugins/CheckClearPlugin.cs | 77 +- src/TouchSocket/Plugins/HeartbeatPlugin.cs | 51 +- .../Plugins/Interfaces/IIdChangedPlugin.cs | 12 +- .../Plugins/Interfaces/ILoadedConfigPlugin.cs | 7 +- .../Interfaces/ILoadingConfigPlugin.cs | 15 +- .../Interfaces/IServerStartedPlugin.cs | 14 +- .../Plugins/Interfaces/IServerStopedPlugin.cs | 8 +- .../Plugins/Interfaces/ITcpConnectedPlugin.cs | 8 +- .../Interfaces/ITcpConnectingPlugin.cs | 8 +- ...tedPlguin.cs => ITcpDisconnectedPlugin.cs} | 10 +- .../Interfaces/ITcpDisconnectingPlugin.cs | 6 +- .../Plugins/Interfaces/ITcpReceivedPlugin.cs | 14 +- .../Plugins/Interfaces/ITcpReceivingPlugin.cs | 14 +- .../Plugins/Interfaces/ITcpSendingPlugin.cs | 6 +- .../Plugins/Interfaces/IUdpReceivedPlugin.cs | 6 +- src/TouchSocket/Plugins/ReconnectionPlugin.cs | 113 ++- src/TouchSocket/TouchSocket.csproj | 48 +- .../WaitingClient/WaitingClient.cs | 8 +- .../WaitingClient/WaitingClientExtension.cs | 1 - 280 files changed, 5213 insertions(+), 3521 deletions(-) delete mode 100644 PerformanceTest.sln rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/BeetleXRpc.cs (100%) rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/NewLifeRpc.cs (100%) rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/Program.cs (100%) rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj (86%) rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/TestController.cs (85%) rename performancetest/{Rpc对比测试 => Rpc}/RpcPerformanceConsoleApp/TouchSocketRpc.cs (70%) create mode 100644 performancetest/Rpc/RpcPerformanceTest.sln create mode 100644 src/Directory.Build.props create mode 100644 src/Keys/TouchSocket.snk rename src/{TouchSocket.JsonRpc/Enum/JRPT.cs => TouchSocket.Dmtp/Features/FileTransfer/Enum/TransferType.cs} (75%) delete mode 100644 src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileOperationEventArgs.cs delete mode 100644 src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferStatusEventArgs.cs rename src/TouchSocket.Dmtp/{Enum/TransferFlags.cs => Features/FileTransfer/EventArgs/FileTransferedEventArgs.cs} (55%) rename src/TouchSocket.Dmtp/{Enum/TransferType.cs => Features/FileTransfer/EventArgs/FileTransferingEventArgs.cs} (52%) create mode 100644 src/TouchSocket.Dmtp/Features/FileTransfer/Extensions/TransferTypeExtension.cs rename src/TouchSocket.Dmtp/Features/Rpc/Actor/{ITargetDmtpRpcActor.cs => TargetDmtpRpcActor.cs} (94%) create mode 100644 src/TouchSocket.Http/Common/Internal/InternalHttpParams.cs create mode 100644 src/TouchSocket.Http/Components/HttpClientSlim.cs rename src/TouchSocket.Http/{Interface => Components/Interfaces}/IHttpClient.cs (88%) create mode 100644 src/TouchSocket.Http/Components/Interfaces/IHttpClientBase.cs rename src/TouchSocket.Http/{Interface => Components/Interfaces}/IHttpService.cs (100%) create mode 100644 src/TouchSocket.Http/Components/Interfaces/IHttpSocketClient.cs create mode 100644 src/TouchSocket.Http/Interface/IHttpParams.cs rename src/TouchSocket.Http/WebSockets/Extensions/{WSClientExtensions.cs => WebSocketClientExtensions.cs} (99%) rename src/TouchSocket.Http/WebSockets/Extensions/{WSDataFrameExtensions.cs => WebSocketDataFrameExtensions.cs} (98%) delete mode 100644 src/TouchSocket.Http/WebSockets/Extensions/WebSocketExtension.cs rename src/TouchSocket.Http/WebSockets/Plugins/{WSCommandLinePlugin.cs => WebSocketCommandLinePlugin.cs} (94%) create mode 100644 src/TouchSocket.JsonRpc/Common/HttpJsonRpcCallContext.cs rename src/TouchSocket.JsonRpc/Common/{JsonRpcCallContext.cs => JsonRpcCallContextBase.cs} (75%) create mode 100644 src/TouchSocket.JsonRpc/Common/JsonRpcError.cs create mode 100644 src/TouchSocket.JsonRpc/Common/TcpJsonRpcCallContext.cs create mode 100644 src/TouchSocket.JsonRpc/Common/WebSocketJsonRpcCallContext.cs create mode 100644 src/TouchSocket.JsonRpc/Components/HttpJsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Components/HttpJsonRpcClientSlim.cs delete mode 100644 src/TouchSocket.JsonRpc/Components/JsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Components/TcpJsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Components/WebSocketJsonRpcClient.cs delete mode 100644 src/TouchSocket.JsonRpc/Config/JsonRpcConfigExtensions.cs create mode 100644 src/TouchSocket.JsonRpc/Extensions/HttpSocketClientExtension.cs create mode 100644 src/TouchSocket.JsonRpc/Extensions/JsonRpcConfigExtension.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcCallContext.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClientSlim.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcCallContext.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Interface/IWebSocketJsonRpcClient.cs create mode 100644 src/TouchSocket.JsonRpc/Plugins/HttpJsonRpcParserPlugin.cs rename src/TouchSocket.JsonRpc/Plugins/{JsonRpcParserPlugin.cs => JsonRpcParserPluginBase.cs} (51%) create mode 100644 src/TouchSocket.JsonRpc/Plugins/TcpJsonRpcParserPlugin.cs create mode 100644 src/TouchSocket.JsonRpc/Plugins/WebSocketJsonRpcParserPlugin.cs create mode 100644 src/TouchSocket.SourceGenerator.Rpc/LICENSE.txt create mode 100644 src/TouchSocket.SourceGenerator.Rpc/logo.ico create mode 100644 src/TouchSocket.SourceGenerator.Rpc/logo.png create mode 100644 src/TouchSocket.WebApi/Components/WebApiClientSlim.cs create mode 100644 src/TouchSocket.WebApi/EventArgs/WebApiEventArgs.cs create mode 100644 src/TouchSocket.WebApi/Interface/IWebApiClientBase.cs create mode 100644 src/TouchSocket.WebApi/Plugins/Interfaces/IWebApiPlugin.cs rename TouchSocket.sln => src/TouchSocket.sln (78%) rename src/TouchSocket/Plugins/Interfaces/{ITcpDisconnectedPlguin.cs => ITcpDisconnectedPlugin.cs} (70%) diff --git a/PerformanceTest.sln b/PerformanceTest.sln deleted file mode 100644 index 9ec7ab5b2..000000000 --- a/PerformanceTest.sln +++ /dev/null @@ -1,30 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.4.33213.308 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Rpc对比测试", "Rpc对比测试", "{49B4FE19-FB5C-4828-B01E-824B616C3563}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RpcPerformanceConsoleApp", "performancetest\Rpc对比测试\RpcPerformanceConsoleApp\RpcPerformanceConsoleApp.csproj", "{942F99CD-B6A9-42A0-9504-969465E69FA6}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {942F99CD-B6A9-42A0-9504-969465E69FA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {942F99CD-B6A9-42A0-9504-969465E69FA6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {942F99CD-B6A9-42A0-9504-969465E69FA6}.Release|Any CPU.ActiveCfg = Release|Any CPU - {942F99CD-B6A9-42A0-9504-969465E69FA6}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {942F99CD-B6A9-42A0-9504-969465E69FA6} = {49B4FE19-FB5C-4828-B01E-824B616C3563} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {72E3B6D3-F2C0-4758-BADC-6EA7CF063120} - EndGlobalSection -EndGlobal diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/BeetleXRpc.cs b/performancetest/Rpc/RpcPerformanceConsoleApp/BeetleXRpc.cs similarity index 100% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/BeetleXRpc.cs rename to performancetest/Rpc/RpcPerformanceConsoleApp/BeetleXRpc.cs diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/NewLifeRpc.cs b/performancetest/Rpc/RpcPerformanceConsoleApp/NewLifeRpc.cs similarity index 100% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/NewLifeRpc.cs rename to performancetest/Rpc/RpcPerformanceConsoleApp/NewLifeRpc.cs diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/Program.cs b/performancetest/Rpc/RpcPerformanceConsoleApp/Program.cs similarity index 100% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/Program.cs rename to performancetest/Rpc/RpcPerformanceConsoleApp/Program.cs diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj b/performancetest/Rpc/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj similarity index 86% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj rename to performancetest/Rpc/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj index 092c7d8d1..2f0eb27c7 100644 --- a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj +++ b/performancetest/Rpc/RpcPerformanceConsoleApp/RpcPerformanceConsoleApp.csproj @@ -11,6 +11,6 @@ - + diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TestController.cs b/performancetest/Rpc/RpcPerformanceConsoleApp/TestController.cs similarity index 85% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TestController.cs rename to performancetest/Rpc/RpcPerformanceConsoleApp/TestController.cs index 1097d4674..d7e0152a0 100644 --- a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TestController.cs +++ b/performancetest/Rpc/RpcPerformanceConsoleApp/TestController.cs @@ -1,10 +1,6 @@ using EventNext; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -using TouchSocket.Rpc.TouchRpc; +using TouchSocket.Dmtp.Rpc; using TouchSocket.Rpc; namespace RpcPerformanceConsoleApp @@ -26,19 +22,19 @@ namespace RpcPerformanceConsoleApp [Service(typeof(ITestTaskController))] public class TestTaskController : ITestTaskController { - [TouchRpc(true)] + [DmtpRpc(true)] public Task Sum(int a, int b) { return Task.FromResult(a + b); } - [TouchRpc(true)] + [DmtpRpc(true)] public Task GetBytes(int length) { return Task.FromResult(new byte[length]); } - [TouchRpc(true)] + [DmtpRpc(true)] public Task GetBigString() { StringBuilder stringBuilder = new StringBuilder(); @@ -53,16 +49,16 @@ namespace RpcPerformanceConsoleApp public class TestController : RpcServer { - [TouchRpc(true)] + [DmtpRpc(true)] public int Sum(int a, int b) => a + b; - [TouchRpc(true)] + [DmtpRpc(true)] public byte[] GetBytes(int length) { return new byte[length]; } - [TouchRpc(true)] + [DmtpRpc(true)] public string GetBigString() { StringBuilder stringBuilder = new StringBuilder(); diff --git a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TouchSocketRpc.cs b/performancetest/Rpc/RpcPerformanceConsoleApp/TouchSocketRpc.cs similarity index 70% rename from performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TouchSocketRpc.cs rename to performancetest/Rpc/RpcPerformanceConsoleApp/TouchSocketRpc.cs index 98af93d4a..ee5ab700a 100644 --- a/performancetest/Rpc对比测试/RpcPerformanceConsoleApp/TouchSocketRpc.cs +++ b/performancetest/Rpc/RpcPerformanceConsoleApp/TouchSocketRpc.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; using TouchSocket.Core; +using TouchSocket.Dmtp; +using TouchSocket.Dmtp.Rpc; using TouchSocket.Rpc; -using TouchSocket.Rpc.TouchRpc; using TouchSocket.Sockets; namespace RpcPerformanceConsoleApp @@ -14,16 +11,20 @@ namespace RpcPerformanceConsoleApp { public static void StartServer() { - var service = new TcpTouchRpcService(); + var service = new TcpDmtpService(); var config = new TouchSocketConfig()//配置 .SetListenIPHosts(new IPHost[] { new IPHost(7789) }) .ConfigureContainer(a => { a.AddConsoleLogger(); }) - .ConfigureRpcStore(a => + .ConfigurePlugins(a => { - a.RegisterServer(); + a.UseDmtpRpc() + .ConfigureRpcStore(store => + { + store.RegisterServer(); + }); }) .SetVerifyToken("TouchRpc");//设定连接口令,作用类似账号密码 @@ -35,17 +36,22 @@ namespace RpcPerformanceConsoleApp public static void StartSumClient(int count) { - TcpTouchRpcClient client = new TcpTouchRpcClient(); + TcpDmtpClient client = new TcpDmtpClient(); client.Setup(new TouchSocketConfig() + .ConfigurePlugins(a => + { + a.UseDmtpRpc(); + }) .SetRemoteIPHost("127.0.0.1:7789") .SetVerifyToken("TouchRpc")); client.Connect(); TimeSpan timeSpan = TimeMeasurer.Run(() => { + var actor= client.GetDmtpRpcActor(); for (int i = 0; i < count; i++) { - var rs = client.Invoke("Sum", InvokeOption.WaitInvoke, i, i); + var rs = actor.InvokeT("Sum", InvokeOption.WaitInvoke, i, i); if (rs != i + i) { Console.WriteLine("调用结果不一致"); @@ -61,17 +67,22 @@ namespace RpcPerformanceConsoleApp public static void StartGetBytesClient(int count) { - TcpTouchRpcClient client = new TcpTouchRpcClient(); + TcpDmtpClient client = new TcpDmtpClient(); client.Setup(new TouchSocketConfig() + .ConfigurePlugins(a => + { + a.UseDmtpRpc(); + }) .SetRemoteIPHost("127.0.0.1:7789") .SetVerifyToken("TouchRpc")); client.Connect(); TimeSpan timeSpan = TimeMeasurer.Run(() => { + var actor = client.GetDmtpRpcActor(); for (int i = 1; i < count; i++) { - var rs = client.Invoke("GetBytes", InvokeOption.WaitInvoke, i);//测试10k数据 + var rs = actor.InvokeT("GetBytes", InvokeOption.WaitInvoke, i);//测试10k数据 if (rs.Length != i) { Console.WriteLine("调用结果不一致"); @@ -87,8 +98,12 @@ namespace RpcPerformanceConsoleApp public static void StartBigStringClient(int count) { - TcpTouchRpcClient client = new TcpTouchRpcClient(); + TcpDmtpClient client = new TcpDmtpClient(); client.Setup(new TouchSocketConfig() + .ConfigurePlugins(a => + { + a.UseDmtpRpc(); + }) .SetRemoteIPHost("127.0.0.1:7789") .SetVerifyToken("TouchRpc")); client.Connect(); @@ -96,9 +111,10 @@ namespace RpcPerformanceConsoleApp TimeSpan timeSpan = TimeMeasurer.Run(() => { + var actor = client.GetDmtpRpcActor(); for (int i = 0; i < count; i++) { - var rs = client.Invoke("GetBigString", InvokeOption.WaitInvoke); + var rs = actor.InvokeT("GetBigString", InvokeOption.WaitInvoke); if (i % 1000 == 0) { Console.WriteLine(i); diff --git a/performancetest/Rpc/RpcPerformanceTest.sln b/performancetest/Rpc/RpcPerformanceTest.sln new file mode 100644 index 000000000..ed5ec694b --- /dev/null +++ b/performancetest/Rpc/RpcPerformanceTest.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33213.308 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RpcPerformanceConsoleApp", "RpcPerformanceConsoleApp\RpcPerformanceConsoleApp.csproj", "{DC26CA80-C08A-43DE-8E2C-AE6129B482EC}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DC26CA80-C08A-43DE-8E2C-AE6129B482EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DC26CA80-C08A-43DE-8E2C-AE6129B482EC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DC26CA80-C08A-43DE-8E2C-AE6129B482EC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DC26CA80-C08A-43DE-8E2C-AE6129B482EC}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {72E3B6D3-F2C0-4758-BADC-6EA7CF063120} + EndGlobalSection +EndGlobal diff --git a/src/Directory.Build.props b/src/Directory.Build.props new file mode 100644 index 000000000..0bc89e5be --- /dev/null +++ b/src/Directory.Build.props @@ -0,0 +1,40 @@ + + + logo.ico + True + ..\Keys\TouchSocket.snk + 2.0.0-beta.140 + true + 8.0 + false + 若汝棋茗 + Copyright © 2023 若汝棋茗 + https://gitee.com/rrqm_home/touchsocket + + true + true + logo.png + 若汝棋茗 + true + LICENSE.txt + ..\..\Build + + https://gitee.com/rrqm_home/touchsocket + + + + true + + + + + True + + + + True + + + + + \ No newline at end of file diff --git a/src/Keys/TouchSocket.snk b/src/Keys/TouchSocket.snk new file mode 100644 index 0000000000000000000000000000000000000000..f101d7eb5645300abcd8afeb9b372ef79099f908 GIT binary patch literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50097*rrF`@zlnJ&8W}a|0IIWW-4LltAkXd$ zuh2O^zWeXgGeFI$XOwAmF{98qF`DQde_x|!gS-<1fCl5c$tBOSFzsdpzU?Vd)CN1d z(A;^Vx2aHx!w7OY7rg@>%6nlMZ`2W|{`Wr?N6Ac#$49y~dg=y-dtGZDFRpT@#YU6A ztFf4OLoG}H#n})3!+ADdfR^G24~aNs!lZMs6XVoDsqo|Gl~p#nZuqBI>rgTZckGG^ zvorfVMsF`F%S6GaqiCSm=B|Ci?YLl@gXw$c-mqGTXsRkUM!ff`q68fE{U;ui$Qj9O zTS0kWyu~jni_|)t)h~atvz>SsTol8lBkY>$Y-e1IA^rtTmQ$!ig|vCWSC(_R<_$ZD zT39PR6ILptb4JCx1GeOQrY`&4oKfdN!a4o`u=&?+V_%?IU%5(Fq}KSY@5>}>t$mr4 z-Wz~RP_N8GGXVDhfGcAt4Z1$0J<0yUe@HcEmC=OD`I$<0$tl%7aP-g)A3COPHSD - /// WebsocketDmtpService + /// WebSocketDmtpService /// - public class WebsocketDmtpService : DisposableObject, IWebsocketDmtpService + public class WebSocketDmtpService : DisposableObject, IWebSocketDmtpService { #region SocketClient - private readonly ConcurrentDictionary m_socketClients = new ConcurrentDictionary(); + private readonly ConcurrentDictionary m_socketClients = new ConcurrentDictionary(); /// /// 数量 @@ -41,7 +41,7 @@ namespace TouchSocket.Dmtp.AspNetCore /// /// /// - public WebsocketDmtpSocketClient this[string id] + public WebSocketDmtpSocketClient this[string id] { get { @@ -54,7 +54,7 @@ namespace TouchSocket.Dmtp.AspNetCore /// 获取所有的客户端 /// /// - public IEnumerable GetClients() + public IEnumerable GetClients() { return this.m_socketClients.Values; } @@ -93,7 +93,7 @@ namespace TouchSocket.Dmtp.AspNetCore /// /// /// - public bool TryGetSocketClient(string id, out WebsocketDmtpSocketClient socketClient) + public bool TryGetSocketClient(string id, out WebSocketDmtpSocketClient socketClient) { if (string.IsNullOrEmpty(id)) { @@ -104,12 +104,12 @@ namespace TouchSocket.Dmtp.AspNetCore return this.m_socketClients.TryGetValue(id, out socketClient); } - internal bool TryAdd(string id, WebsocketDmtpSocketClient socketClient) + internal bool TryAdd(string id, WebSocketDmtpSocketClient socketClient) { return this.m_socketClients.TryAdd(id, socketClient); } - internal bool TryRemove(string id, out WebsocketDmtpSocketClient socketClient) + internal bool TryRemove(string id, out WebSocketDmtpSocketClient socketClient) { if (string.IsNullOrEmpty(id)) { @@ -124,10 +124,10 @@ namespace TouchSocket.Dmtp.AspNetCore private long m_idCount; /// - /// 创建一个基于Websocket的Dmtp服务器。 + /// 创建一个基于WebSocket的Dmtp服务器。 /// /// - public WebsocketDmtpService(TouchSocketConfig config) + public WebSocketDmtpService(TouchSocketConfig config) { if (config == null) { @@ -199,7 +199,7 @@ namespace TouchSocket.Dmtp.AspNetCore { return; } - if (this.m_socketClients.TryGetValue(oldId, out WebsocketDmtpSocketClient socketClient)) + if (this.m_socketClients.TryGetValue(oldId, out var socketClient)) { socketClient.ResetId(newId); } @@ -220,7 +220,7 @@ namespace TouchSocket.Dmtp.AspNetCore { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); var id = this.GetDefaultNewId(); - var client = new WebsocketDmtpSocketClient(); + var client = new WebSocketDmtpSocketClient(); if (!this.TryAdd(id, client)) { throw new Exception("Id重复"); @@ -289,7 +289,7 @@ namespace TouchSocket.Dmtp.AspNetCore this.Container = container; this.PluginsManager = pluginsManager; } - private DmtpActor CreateDmtpActor(WebsocketDmtpSocketClient client) + private DmtpActor CreateDmtpActor(WebSocketDmtpSocketClient client) { return new DmtpActor(true) { diff --git a/src/TouchSocket.AspNetCore/Smtp/Components/WebsocketSmtpSocketClient.cs b/src/TouchSocket.AspNetCore/Smtp/Components/WebsocketSmtpSocketClient.cs index b46c49d6c..537ee379b 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Components/WebsocketSmtpSocketClient.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Components/WebsocketSmtpSocketClient.cs @@ -22,15 +22,15 @@ using TouchSocket.Sockets; namespace TouchSocket.Dmtp.AspNetCore { /// - /// WebsocketDmtpSocketClient + /// WebSocketDmtpSocketClient /// - public class WebsocketDmtpSocketClient : DependencyObject, IWebsocketDmtpSocketClient + public class WebSocketDmtpSocketClient : DependencyObject, IWebSocketDmtpSocketClient { private readonly object m_syncRoot = new object(); private WebSocket m_client; private DmtpActor m_smtpActor; private TcpDmtpAdapter m_smtpAdapter; - private WebsocketDmtpService m_service; + private WebSocketDmtpService m_service; public int BufferLength { get; private set; } @@ -64,10 +64,10 @@ namespace TouchSocket.Dmtp.AspNetCore public IPluginsManager PluginsManager { get; private set; } public Protocol Protocol { get; set; } = DmtpUtility.DmtpProtocol; - public IWebsocketDmtpService Service { get => m_service; } + public IWebSocketDmtpService Service { get => this.m_service; } /// - public IDmtpActor DmtpActor { get => m_smtpActor; } + public IDmtpActor DmtpActor { get => this.m_smtpActor; } /// public int VerifyTimeout => this.Config.GetValue(DmtpConfigExtension.VerifyTimeoutProperty); @@ -118,7 +118,7 @@ namespace TouchSocket.Dmtp.AspNetCore this.m_smtpAdapter.Config(config); - this.SetBufferLength(this.Config.GetValue(TouchSocketConfigExtension.BufferLengthProperty) ?? 1024 * 64) ; + this.SetBufferLength(this.Config.GetValue(TouchSocketConfigExtension.BufferLengthProperty) ?? 1024 * 64); } internal void InternalSetContainer(IContainer container) @@ -137,7 +137,7 @@ namespace TouchSocket.Dmtp.AspNetCore this.PluginsManager = pluginsManager; } - internal void InternalSetService(WebsocketDmtpService service) + internal void InternalSetService(WebSocketDmtpService service) { this.m_service = service; } @@ -282,9 +282,9 @@ namespace TouchSocket.Dmtp.AspNetCore { while (true) { - using (var byteBlock=new ByteBlock(this.BufferLength)) + using (var byteBlock = new ByteBlock(this.BufferLength)) { - var result = await this.m_client.ReceiveAsync(new ArraySegment(byteBlock.Buffer,0,byteBlock.Capacity), default); + var result = await this.m_client.ReceiveAsync(new ArraySegment(byteBlock.Buffer, 0, byteBlock.Capacity), default); if (result.Count == 0) { break; @@ -367,7 +367,7 @@ namespace TouchSocket.Dmtp.AspNetCore { if (this.PluginsManager.Enable) { - this.PluginsManager.RaiseAsync(nameof(ITcpDisconnectedPlguin.OnTcpDisconnected), this, new DisconnectEventArgs(manual, msg)); + this.PluginsManager.RaiseAsync(nameof(ITcpDisconnectedPlugin.OnTcpDisconnected), this, new DisconnectEventArgs(manual, msg)); } } } diff --git a/src/TouchSocket.AspNetCore/Smtp/Extensions/ApplicationBuilderExtensions.cs b/src/TouchSocket.AspNetCore/Smtp/Extensions/ApplicationBuilderExtensions.cs index e2b2cf7a4..d43669330 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Extensions/ApplicationBuilderExtensions.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Extensions/ApplicationBuilderExtensions.cs @@ -26,9 +26,9 @@ namespace Microsoft.AspNetCore.Builder /// /// /// - public static IApplicationBuilder UseWebsocketDmtp(this IApplicationBuilder builder, string url = "/websocketsmtp") + public static IApplicationBuilder UseWebSocketDmtp(this IApplicationBuilder builder, string url = "/websocketsmtp") { - return builder.UseMiddleware(url); + return builder.UseMiddleware(url); } } } \ No newline at end of file diff --git a/src/TouchSocket.AspNetCore/Smtp/Extensions/WebsocketSmtpServiceExtensions.cs b/src/TouchSocket.AspNetCore/Smtp/Extensions/WebsocketSmtpServiceExtensions.cs index 9534840c5..d1315bb8b 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Extensions/WebsocketSmtpServiceExtensions.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Extensions/WebsocketSmtpServiceExtensions.cs @@ -17,19 +17,19 @@ using TouchSocket.Dmtp.AspNetCore; namespace Microsoft.Extensions.DependencyInjection { /// - /// WebsocketDmtpServiceExtensions + /// WebSocketDmtpServiceExtensions /// - public static class WebsocketDmtpServiceExtensions + public static class WebSocketDmtpServiceExtensions { /// - /// 添加服务。 + /// 添加服务。 /// /// /// /// - public static IServiceCollection AddWebsocketDmtpService(this IServiceCollection service, Func config) + public static IServiceCollection AddWebSocketDmtpService(this IServiceCollection service, Func config) { - return service.AddSingleton(new WebsocketDmtpService(config.Invoke())); + return service.AddSingleton(new WebSocketDmtpService(config.Invoke())); } } } \ No newline at end of file diff --git a/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpService.cs b/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpService.cs index e82c617bb..da103ad78 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpService.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpService.cs @@ -12,18 +12,16 @@ //------------------------------------------------------------------------------ using Microsoft.AspNetCore.Http; -using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Dmtp; namespace TouchSocket.Dmtp.AspNetCore { /// - /// IWebsocketDmtpService服务器接口 + /// IWebSocketDmtpService服务器接口 /// - public interface IWebsocketDmtpService : IDmtpService, IPluginObject + public interface IWebSocketDmtpService : IDmtpService, IPluginObject { /// /// 配置项 @@ -48,7 +46,7 @@ namespace TouchSocket.Dmtp.AspNetCore /// 获取所有的客户端 /// /// - IEnumerable GetClients(); + IEnumerable GetClients(); /// /// 获取所有在线客户端的Id集合。 diff --git a/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpSocketClient.cs b/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpSocketClient.cs index beb738348..7e5a62001 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpSocketClient.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Interfaces/IWebsocketSmtpSocketClient.cs @@ -1,11 +1,8 @@ using Microsoft.AspNetCore.Http; -using System; -using System.Collections.Generic; -using System.Text; namespace TouchSocket.Dmtp.AspNetCore { - public interface IWebsocketDmtpSocketClient : IWebsocketDmtpClientBase + public interface IWebSocketDmtpSocketClient : IWebSocketDmtpClientBase { /// /// Http上下文 @@ -15,6 +12,6 @@ namespace TouchSocket.Dmtp.AspNetCore /// /// 包含该客户端的服务器。 /// - IWebsocketDmtpService Service { get; } + IWebSocketDmtpService Service { get; } } } diff --git a/src/TouchSocket.AspNetCore/Smtp/Middlewares/WebsocketSmtpMiddleware.cs b/src/TouchSocket.AspNetCore/Smtp/Middlewares/WebsocketSmtpMiddleware.cs index 50533931f..97857a8ae 100644 --- a/src/TouchSocket.AspNetCore/Smtp/Middlewares/WebsocketSmtpMiddleware.cs +++ b/src/TouchSocket.AspNetCore/Smtp/Middlewares/WebsocketSmtpMiddleware.cs @@ -11,19 +11,18 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; namespace TouchSocket.Dmtp.AspNetCore { /// - /// WebsocketDmtpMiddleware中间件 + /// WebSocketDmtpMiddleware中间件 /// - public class WebsocketDmtpMiddleware + public class WebSocketDmtpMiddleware { private readonly RequestDelegate m_next; - private readonly IWebsocketDmtpService m_websocketDmtpService; + private readonly IWebSocketDmtpService m_websocketDmtpService; private string m_url = "/websocketsmtp"; /// @@ -32,7 +31,7 @@ namespace TouchSocket.Dmtp.AspNetCore /// /// /// - public WebsocketDmtpMiddleware(string m_url, RequestDelegate next, IWebsocketDmtpService rpcService) + public WebSocketDmtpMiddleware(string m_url, RequestDelegate next, IWebSocketDmtpService rpcService) { this.Url = m_url; this.m_next = next ?? throw new ArgumentNullException(nameof(next)); @@ -42,10 +41,11 @@ namespace TouchSocket.Dmtp.AspNetCore /// /// Url /// - public string Url - { - get => this.m_url; - set => this.m_url = string.IsNullOrEmpty(value) ? "/websocketsmtp" : value; } + public string Url + { + get => this.m_url; + set => this.m_url = string.IsNullOrEmpty(value) ? "/websocketsmtp" : value; + } /// /// diff --git a/src/TouchSocket.AspNetCore/Sockets/Extensions/SocketsServiceCollectionExtensions.cs b/src/TouchSocket.AspNetCore/Sockets/Extensions/SocketsServiceCollectionExtensions.cs index 159dff42a..f0aaf4397 100644 --- a/src/TouchSocket.AspNetCore/Sockets/Extensions/SocketsServiceCollectionExtensions.cs +++ b/src/TouchSocket.AspNetCore/Sockets/Extensions/SocketsServiceCollectionExtensions.cs @@ -24,45 +24,44 @@ namespace Microsoft.Extensions.DependencyInjection #region TcpService /// - /// 添加TcpService服务。 + /// 添加服务。并且以TService作为注册接口。 /// - /// 注册服务的接口 + /// 注册服务的接口 /// /// 实例化的服务器 /// - public static ITcpService AddTcpService(this IServiceCollection service, ITcpService tcpService) where ServiceInterface : ITcpService + public static TService AddTcpService(this IServiceCollection service, ITcpService tcpService) + where TService : class, ITcpService { - tcpService.Container.RegisterSingleton(tcpService); - return (ServiceInterface)tcpService; + service.AddSingleton((provider) => (TService)tcpService); + return (TService)tcpService; } /// - /// 添加TcpService服务。 + /// 添加服务。 /// - /// 注册服务的接口 + /// 注册服务的接口 /// - /// 设置配置相关信息 + /// 设置配置相关信息 /// - public static ITcpService AddTcpService(this IServiceCollection service, Action configAction) where ServiceInterface : ITcpService + public static TService AddTcpService(this IServiceCollection service, Func configFunc) where TService : class, ITcpService, new() { - TouchSocketConfig config = new TouchSocketConfig(); - configAction?.Invoke(config); - ITcpService tcpService = new TcpService(); - tcpService.Setup(config) + var tcpService = new TService(); + tcpService.Setup(configFunc.Invoke()) .Start(); - return AddTcpService(service, tcpService); + return (TService)AddTcpService(service, tcpService); } /// /// 以作为注入接口,添加TcpService服务。 /// /// - /// 设置配置相关信息 + /// 设置配置相关信息 /// - public static ITcpService AddTcpService(this IServiceCollection service, Action configAction) + public static ITcpService AddTcpService(this IServiceCollection service, Func configFunc) { - return AddTcpService(service, configAction); + return AddTcpService(service, configFunc); } /// @@ -73,12 +72,55 @@ namespace Microsoft.Extensions.DependencyInjection /// public static ITcpService AddTcpService(this IServiceCollection service, int port) { - return AddTcpService(service, config => + return AddTcpService(service, () => { - config.SetListenIPHosts(new IPHost[] { new IPHost(port) }); + return new TouchSocketConfig().SetListenIPHosts(new IPHost[] { new IPHost(port) }); }); } #endregion TcpService + + #region UdpSession + /// + /// 添加服务。以TUdpSession泛型为注册接口。 + /// + /// 注册服务的接口 + /// + /// 实例化的UdpSession + /// + public static TUdpSession AddUdpSession(this IServiceCollection service, IUdpSession udpSession) where TUdpSession : class, IUdpSession + { + service.AddSingleton((p) => (TUdpSession)udpSession); + return (TUdpSession)udpSession; + } + + /// + /// 添加服务。以TUdpSession泛型为注册接口。 + /// + /// 注册服务的接口 + /// + /// + public static TUdpSession AddUdpSession(this IServiceCollection service, Func configFunc) where TUdpSession : class, IUdpSession, new() + { + var udpSession = new TUdpSession(); + udpSession.Setup(configFunc.Invoke()); + udpSession.Start(); + return AddUdpSession(service, udpSession); + } + + /// + /// 添加服务。以为注册接口。 + /// + /// + /// + /// + public static IUdpSession AddUdpSession(this IServiceCollection service, Func configFunc) + { + var udpSession = new UdpSession(); + udpSession.Setup(configFunc.Invoke()); + udpSession.Start(); + return AddUdpSession(service, udpSession); + } + #endregion } } \ No newline at end of file diff --git a/src/TouchSocket.AspNetCore/TouchSocket.AspNetCore.csproj b/src/TouchSocket.AspNetCore/TouchSocket.AspNetCore.csproj index e0a091efd..d3ecada4d 100644 --- a/src/TouchSocket.AspNetCore/TouchSocket.AspNetCore.csproj +++ b/src/TouchSocket.AspNetCore/TouchSocket.AspNetCore.csproj @@ -1,66 +1,27 @@ - netcoreapp3.1;net7.0 + net6.0;net7.0 logo.ico - false - - 2.0.0-beta.2 - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 message;arraypool;logger;plugin - - 这是一个适用于AspNetCore的、轻量级的、支持插件的综合网络通信库。 + 这是一个适用于AspNetCore的、轻量级的、支持插件的综合网络通信库。 - 说明文档:http://rrqm_home.gitee.io/touchsocket - - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt +说明文档:http://rrqm_home.gitee.io/touchsocket TouchSocket.AspNetCore - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.AspNetCore + ..\..\Build\NugetPackages\TouchSocket.AspNetCore - - True - - - - True - - - - - - + - - - - - - - - - - - - - - + + + + True + Embedded + True + diff --git a/src/TouchSocket.CodeAnalyzer/TouchSocket.CodeAnalyzer.csproj b/src/TouchSocket.CodeAnalyzer/TouchSocket.CodeAnalyzer.csproj index f6616fd31..50520da80 100644 --- a/src/TouchSocket.CodeAnalyzer/TouchSocket.CodeAnalyzer.csproj +++ b/src/TouchSocket.CodeAnalyzer/TouchSocket.CodeAnalyzer.csproj @@ -1,43 +1,12 @@ net45;netstandard2.0; - false - logo.ico - true - D:\MyStore\13_Doc\Keys\TouchSocketPro.snk - 2.0.0-beta - true - 若汝棋茗 - Copyright © 2023 若汝棋茗 rpc,analyzer - - 这是可以让TouchSocket.Rpc拥有代码分析功能的库。 - - https://gitee.com/rrqm_home/touchsocket - - logo.png - 若汝棋茗 - LICENSE.txt - true + 这是可以让TouchSocket.Rpc拥有代码分析功能的库。 TouchSocket.CodeAnalyzer - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.CodeAnalyzer + ..\..\Build\NugetPackages\TouchSocket.CodeAnalyzer - - - - True - - - - True - - - - diff --git a/src/TouchSocket.Core.DependencyInjection/Common/AspNetCoreContainer.cs b/src/TouchSocket.Core.DependencyInjection/Common/AspNetCoreContainer.cs index efa8f3e3f..cb8b50ae6 100644 --- a/src/TouchSocket.Core.DependencyInjection/Common/AspNetCoreContainer.cs +++ b/src/TouchSocket.Core.DependencyInjection/Common/AspNetCoreContainer.cs @@ -89,8 +89,8 @@ namespace TouchSocket.Core.AspNetCore { fromType = fromType.GetGenericTypeDefinition(); } - ServiceDescriptor[] array = this.m_services.ToArray(); - foreach (ServiceDescriptor item in array) + var array = this.m_services.ToArray(); + foreach (var item in array) { if (item.ServiceType == fromType) { @@ -154,8 +154,8 @@ namespace TouchSocket.Core.AspNetCore /// public void Unregister(DependencyDescriptor descriptor, string key = "") { - ServiceDescriptor[] array = this.m_services.ToArray(); - foreach (ServiceDescriptor item in array) + var array = this.m_services.ToArray(); + foreach (var item in array) { if (item.ServiceType == descriptor.FromType) { diff --git a/src/TouchSocket.Core.DependencyInjection/TouchSocket.Core.DependencyInjection.csproj b/src/TouchSocket.Core.DependencyInjection/TouchSocket.Core.DependencyInjection.csproj index 8f3963c86..1cfdae452 100644 --- a/src/TouchSocket.Core.DependencyInjection/TouchSocket.Core.DependencyInjection.csproj +++ b/src/TouchSocket.Core.DependencyInjection/TouchSocket.Core.DependencyInjection.csproj @@ -1,53 +1,26 @@ - net461;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net461;netstandard2.0;net6.0;net7.0 IOC;DependencyInjection 这是为TouchSocket.Core基于IServiceCollection构建的容器扩展包。 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt TouchSocket.Core.DependencyInjection - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.Core.DependencyInjection + ..\..\Build\NugetPackages\TouchSocket.Core.DependencyInjection - - - True - - - - True - - - - - - - - + + + + + True + Embedded + True + diff --git a/src/TouchSocket.Core/Args/MsgEventArgs.cs b/src/TouchSocket.Core/Args/MsgEventArgs.cs index 254cae532..859ff7b37 100644 --- a/src/TouchSocket.Core/Args/MsgEventArgs.cs +++ b/src/TouchSocket.Core/Args/MsgEventArgs.cs @@ -1,15 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TouchSocket.Core +namespace TouchSocket.Core { /// /// MsgEventArgs /// - public class MsgEventArgs: PluginEventArgs + public class MsgEventArgs : PluginEventArgs { /// /// 构造函数 diff --git a/src/TouchSocket.Core/Common/Enum/ResultCode.cs b/src/TouchSocket.Core/Common/Enum/ResultCode.cs index 2a87d9609..99f15354c 100644 --- a/src/TouchSocket.Core/Common/Enum/ResultCode.cs +++ b/src/TouchSocket.Core/Common/Enum/ResultCode.cs @@ -16,7 +16,7 @@ namespace TouchSocket.Core /// /// 结果类型 /// - public enum ResultCode + public enum ResultCode:byte { /// /// 默认 diff --git a/src/TouchSocket.Core/Common/Metadata.cs b/src/TouchSocket.Core/Common/Metadata.cs index 7c7b9cce3..c4773bb32 100644 --- a/src/TouchSocket.Core/Common/Metadata.cs +++ b/src/TouchSocket.Core/Common/Metadata.cs @@ -10,7 +10,7 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.Collections.Specialized; +using System.Collections.Generic; namespace TouchSocket.Core { @@ -18,8 +18,25 @@ namespace TouchSocket.Core /// 元数据键值对。 /// [FastConverter(typeof(MetadataFastBinaryConverter))] - public class Metadata : NameValueCollection, IPackage + public class Metadata : Dictionary, IPackage { + /// + /// + /// + /// + /// + public new string this[string key] + { + get + { + if (this.TryGetValue(key, out var value)) + { + return value; + } + return null; + } + } + /// /// 添加。如果键存在,将被覆盖。 /// @@ -35,10 +52,10 @@ namespace TouchSocket.Core /// 打包 /// /// - public void Package(ByteBlock byteBlock) + public void Package(in ByteBlock byteBlock) { byteBlock.Write(this.Count); - foreach (var item in this.AllKeys) + foreach (var item in this.Keys) { byteBlock.Write(item); byteBlock.Write(this[item]); @@ -49,7 +66,7 @@ namespace TouchSocket.Core /// 解包 /// /// - public void Unpackage(ByteBlock byteBlock) + public void Unpackage(in ByteBlock byteBlock) { var count = byteBlock.ReadInt32(); for (var i = 0; i < count; i++) diff --git a/src/TouchSocket.Core/Common/MetadataFastBinaryConverter.cs b/src/TouchSocket.Core/Common/MetadataFastBinaryConverter.cs index 03704f835..a81afd928 100644 --- a/src/TouchSocket.Core/Common/MetadataFastBinaryConverter.cs +++ b/src/TouchSocket.Core/Common/MetadataFastBinaryConverter.cs @@ -32,7 +32,7 @@ namespace TouchSocket.Core protected override int Write(ByteBlock byteBlock, Metadata obj) { var pos = byteBlock.Pos; - foreach (var item in obj.AllKeys) + foreach (var item in obj.Keys) { byteBlock.Write(item); byteBlock.Write(obj[item]); diff --git a/src/TouchSocket.Core/Data/MD5.cs b/src/TouchSocket.Core/Data/MD5.cs index 31e94fc4b..2f26f1ca4 100644 --- a/src/TouchSocket.Core/Data/MD5.cs +++ b/src/TouchSocket.Core/Data/MD5.cs @@ -10,6 +10,7 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using System.IO; using System.Text; namespace TouchSocket.Core @@ -37,6 +38,24 @@ namespace TouchSocket.Core return sb.ToString(); } + /// + /// 从流中获取MD5值。 + /// + /// + /// + public static string GetMD5Hash(Stream stream) + { + var sb = new StringBuilder(); + using (var crypto = System.Security.Cryptography.MD5.Create()) + { + var data = crypto.ComputeHash(stream); + var length = data.Length; + for (var i = 0; i < length; i++) + sb.Append(data[i].ToString("X2")); + } + return sb.ToString(); + } + /// /// 从字节获取MD5值 /// @@ -78,5 +97,7 @@ namespace TouchSocket.Core var hashOfInput = GetMD5Hash(str); return hashOfInput.CompareTo(hash) == 0; } + + } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Dependency/ContainerExtension.cs b/src/TouchSocket.Core/Dependency/ContainerExtension.cs index 770347c1b..3881e20d2 100644 --- a/src/TouchSocket.Core/Dependency/ContainerExtension.cs +++ b/src/TouchSocket.Core/Dependency/ContainerExtension.cs @@ -184,7 +184,7 @@ namespace TouchSocket.Core /// /// /// - public static IContainer RegisterSingleton(this IContainer container,Type fromType, Func func, string key = "") + public static IContainer RegisterSingleton(this IContainer container, Type fromType, Func func, string key = "") { container.Register(new DependencyDescriptor(fromType, Lifetime.Singleton) { diff --git a/src/TouchSocket.Core/Dependency/DependencyObject.cs b/src/TouchSocket.Core/Dependency/DependencyObject.cs index 6d59c2675..b4a333e61 100644 --- a/src/TouchSocket.Core/Dependency/DependencyObject.cs +++ b/src/TouchSocket.Core/Dependency/DependencyObject.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System.Collections.Generic; -using System.Threading; namespace TouchSocket.Core { @@ -21,7 +20,6 @@ namespace TouchSocket.Core /// public class DependencyObject : DisposableObject, IDependencyObject { - [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)] private readonly Dictionary m_dp = new Dictionary(); /// diff --git a/src/TouchSocket.Core/Dependency/DependencyProperty.cs b/src/TouchSocket.Core/Dependency/DependencyProperty.cs index db1d0b32b..3e0123207 100644 --- a/src/TouchSocket.Core/Dependency/DependencyProperty.cs +++ b/src/TouchSocket.Core/Dependency/DependencyProperty.cs @@ -81,7 +81,7 @@ namespace TouchSocket.Core /// public static DependencyProperty Register(string propertyName, TValue value) { - var dp = new DependencyProperty(propertyName,value); + var dp = new DependencyProperty(propertyName, value); return dp; } diff --git a/src/TouchSocket.Core/Dependency/IContainer.cs b/src/TouchSocket.Core/Dependency/IContainer.cs index b018f6619..3ddb173ba 100644 --- a/src/TouchSocket.Core/Dependency/IContainer.cs +++ b/src/TouchSocket.Core/Dependency/IContainer.cs @@ -19,7 +19,7 @@ namespace TouchSocket.Core /// /// 注入容器接口 /// - public interface IContainer :IEnumerable + public interface IContainer : IEnumerable { /// /// 创建目标类型的对应实例。 diff --git a/src/TouchSocket.Core/Dependency/IDependencyObject.cs b/src/TouchSocket.Core/Dependency/IDependencyObject.cs index edd92a0ac..9463d69c8 100644 --- a/src/TouchSocket.Core/Dependency/IDependencyObject.cs +++ b/src/TouchSocket.Core/Dependency/IDependencyObject.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TouchSocket.Core { diff --git a/src/TouchSocket.Core/Dependency/IDependencyProperty.cs b/src/TouchSocket.Core/Dependency/IDependencyProperty.cs index c378af602..88d55a279 100644 --- a/src/TouchSocket.Core/Dependency/IDependencyProperty.cs +++ b/src/TouchSocket.Core/Dependency/IDependencyProperty.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TouchSocket.Core +namespace TouchSocket.Core { /// /// IDependencyProperty diff --git a/src/TouchSocket.Core/Extensions/BytesExtension.cs b/src/TouchSocket.Core/Extensions/BytesExtension.cs index 585debc7e..9ded107b2 100644 --- a/src/TouchSocket.Core/Extensions/BytesExtension.cs +++ b/src/TouchSocket.Core/Extensions/BytesExtension.cs @@ -61,6 +61,10 @@ namespace TouchSocket.Core else { hitLength = 0; + if (srcByteArray[i] == subByteArray[hitLength]) + { + hitLength++; + } } if (hitLength == subByteArray.Length) @@ -102,6 +106,10 @@ namespace TouchSocket.Core else { hitLength = 0; + if (srcByteArray[i] == subByteArray[hitLength]) + { + hitLength++; + } } if (hitLength == subByteArray.Length) diff --git a/src/TouchSocket.Core/Extensions/RangeExtension.cs b/src/TouchSocket.Core/Extensions/RangeExtension.cs index 3e62ae4d1..f7d6b8611 100644 --- a/src/TouchSocket.Core/Extensions/RangeExtension.cs +++ b/src/TouchSocket.Core/Extensions/RangeExtension.cs @@ -49,14 +49,14 @@ namespace TouchSocket.Core { throw new NotSupportedException("不支持无限枚举。"); } - m_current = range.Start.Value - 1; - m_end = range.End.Value; + this.m_current = range.Start.Value - 1; + this.m_end = range.End.Value; } /// /// Current /// - public int Current => m_current; + public int Current => this.m_current; /// /// MoveNext @@ -64,8 +64,8 @@ namespace TouchSocket.Core /// public bool MoveNext() { - m_current++; - return m_current <= m_end; + this.m_current++; + return this.m_current <= this.m_end; } } #endif diff --git a/src/TouchSocket.Core/Flow/Counter.cs b/src/TouchSocket.Core/Flow/Counter.cs index e4c2baf8b..6cde4a56c 100644 --- a/src/TouchSocket.Core/Flow/Counter.cs +++ b/src/TouchSocket.Core/Flow/Counter.cs @@ -26,7 +26,7 @@ namespace TouchSocket.Core /// /// 最后一次递增时间 /// - public DateTime LastIncrement { get => m_lastIncrement;} + public DateTime LastIncrement { get => this.m_lastIncrement; } /// /// 计数周期 @@ -43,7 +43,7 @@ namespace TouchSocket.Core bool isPeriod; if (DateTime.Now - this.LastIncrement > this.Period) { - Interlocked.Exchange(ref this.m_count,0); + Interlocked.Exchange(ref this.m_count, 0); isPeriod = false; this.m_lastIncrement = DateTime.Now; } diff --git a/src/TouchSocket.Core/Flow/FlowGate.cs b/src/TouchSocket.Core/Flow/FlowGate.cs index 3c4cedaea..bb924c912 100644 --- a/src/TouchSocket.Core/Flow/FlowGate.cs +++ b/src/TouchSocket.Core/Flow/FlowGate.cs @@ -42,7 +42,7 @@ namespace TouchSocket.Core if (this.m_count > this.Maximum) { var time = (DateTime.Now - this.LastIncrement); - var waitTime = this.Period - time <= TimeSpan.Zero ? TimeSpan.Zero : (GetBaseTime() - time); + var waitTime = this.Period - time <= TimeSpan.Zero ? TimeSpan.Zero : (this.GetBaseTime() - time); Thread.Sleep(waitTime); } } @@ -60,7 +60,7 @@ namespace TouchSocket.Core if (this.m_count > this.Maximum) { var time = (DateTime.Now - this.LastIncrement); - var waitTime = this.Period - time <= TimeSpan.Zero ? TimeSpan.Zero : (GetBaseTime() - time); + var waitTime = this.Period - time <= TimeSpan.Zero ? TimeSpan.Zero : (this.GetBaseTime() - time); await Task.Delay(waitTime); } } diff --git a/src/TouchSocket.Core/IO/ConsoleAction.cs b/src/TouchSocket.Core/IO/ConsoleAction.cs index 43e7b2d05..e6ff58456 100644 --- a/src/TouchSocket.Core/IO/ConsoleAction.cs +++ b/src/TouchSocket.Core/IO/ConsoleAction.cs @@ -20,8 +20,33 @@ namespace TouchSocket.Core /// 控制台行为 /// - public partial class ConsoleAction + internal struct VAction { + /// + /// 构造函数 + /// + /// + /// + /// + public VAction(string description, string fullOrder, Action action) + { + this.FullOrder = fullOrder; + this.Action = action ?? throw new ArgumentNullException(nameof(action)); + this.Description = description ?? throw new ArgumentNullException(nameof(description)); + } + + public Action Action { get; } + + public string Description { get; } + public string FullOrder { get; } + } + + /// + /// 控制台行为 + /// + public class ConsoleAction + { + private readonly Dictionary m_actions = new Dictionary(); /// /// 构造函数 @@ -54,35 +79,15 @@ namespace TouchSocket.Core } /// - /// 显示所有注册指令 + /// 执行异常 /// - public void ShowAll() - { - var max = this.actions.Values.Max(a => a.FullOrder.Length) + 8; - - var s = new List(); - foreach (var item in this.actions) - { - if (!s.Contains(item.Value.FullOrder.ToLower())) - { - s.Add(item.Value.FullOrder.ToLower()); - Console.Write($"[{item.Value.FullOrder}]"); - for (var i = 0; i < max - item.Value.FullOrder.Length; i++) - { - Console.Write("-"); - } - Console.WriteLine(item.Value.Description); - } - } - } + public event Action OnException; /// /// 帮助信息指令 /// public string HelpOrder { get; private set; } - private readonly Dictionary actions = new Dictionary(); - /// /// 添加 /// @@ -94,14 +99,24 @@ namespace TouchSocket.Core var orders = order.ToLower().Split('|'); foreach (var item in orders) { - this.actions.Add(item, new VAction(description, order, action)); + this.m_actions.Add(item, new VAction(description, order, action)); } } /// - /// 执行异常 + /// 运行 /// - public event Action OnException; + public void RunCommandLine() + { + while (true) + { + var str=Console.ReadLine(); + if (!this.Run(str)) + { + Console.WriteLine($"没有这个指令。"); + } + } + } /// /// 执行,返回值仅表示是否有这个指令,异常获取请使用 @@ -110,7 +125,7 @@ namespace TouchSocket.Core /// public bool Run(string order) { - if (this.actions.TryGetValue(order.ToLower(), out var vAction)) + if (this.m_actions.TryGetValue(order.ToLower(), out var vAction)) { try { @@ -127,27 +142,28 @@ namespace TouchSocket.Core return false; } } - } - - internal struct VAction - { - public Action Action { get; } - - public string FullOrder { get; } /// - /// 构造函数 + /// 显示所有注册指令 /// - /// - /// - /// - public VAction(string description, string fullOrder, Action action) + public void ShowAll() { - this.FullOrder = fullOrder; - this.Action = action ?? throw new ArgumentNullException(nameof(action)); - this.Description = description ?? throw new ArgumentNullException(nameof(description)); - } + var max = this.m_actions.Values.Max(a => a.FullOrder.Length) + 8; - public string Description { get; } + var s = new List(); + foreach (var item in this.m_actions) + { + if (!s.Contains(item.Value.FullOrder.ToLower())) + { + s.Add(item.Value.FullOrder.ToLower()); + Console.Write($"[{item.Value.FullOrder}]"); + for (var i = 0; i < max - item.Value.FullOrder.Length; i++) + { + Console.Write("-"); + } + Console.WriteLine(item.Value.Description); + } + } + } } } \ No newline at end of file diff --git a/src/TouchSocket.Core/IO/FileIO/FilePool.cs b/src/TouchSocket.Core/IO/FileIO/FilePool.cs index 23061372f..f0454dddb 100644 --- a/src/TouchSocket.Core/IO/FileIO/FilePool.cs +++ b/src/TouchSocket.Core/IO/FileIO/FilePool.cs @@ -14,7 +14,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading; using System.Threading.Tasks; using TouchSocket.Resources; @@ -35,7 +34,7 @@ namespace TouchSocket.Core static FilePool() { - m_timer = new Timer(OnTimer, null, 1000*60, 1000 * 60); + m_timer = new Timer(OnTimer, null, 1000 * 60, 1000 * 60); } /// @@ -261,7 +260,7 @@ namespace TouchSocket.Core private static void DelayRunReleaseFile(string path, int time) { - Task.Run(async() => + Task.Run(async () => { await Task.Delay(time); if (GetReferenceCount(path) == 0) diff --git a/src/TouchSocket.Core/Logger/FileLogger.cs b/src/TouchSocket.Core/Logger/FileLogger.cs index 0a4d2f2a8..e54f41b88 100644 --- a/src/TouchSocket.Core/Logger/FileLogger.cs +++ b/src/TouchSocket.Core/Logger/FileLogger.cs @@ -46,7 +46,7 @@ namespace TouchSocket.Core ~FileLogger() { // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 - Dispose(disposing: false); + this.Dispose(disposing: false); } /// @@ -60,7 +60,7 @@ namespace TouchSocket.Core public void Dispose() { // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中 - Dispose(disposing: true); + this.Dispose(disposing: true); GC.SuppressFinalize(this); } @@ -70,7 +70,7 @@ namespace TouchSocket.Core /// protected virtual void Dispose(bool disposing) { - if (!m_disposedValue) + if (!this.m_disposedValue) { if (disposing) { @@ -78,7 +78,7 @@ namespace TouchSocket.Core } this.m_writer?.Dispose(); - m_disposedValue = true; + this.m_disposedValue = true; } } @@ -115,7 +115,7 @@ namespace TouchSocket.Core { lock (this.m_lock) { - if (this.m_writer == null||this.m_writer.DisposedValue) + if (this.m_writer == null || this.m_writer.DisposedValue) { var dir = Path.Combine(this.m_rootPath, DateTime.Now.ToString("[yyyy-MM-dd]")); if (!Directory.Exists(dir)) diff --git a/src/TouchSocket.Core/Logger/LoggerBase.cs b/src/TouchSocket.Core/Logger/LoggerBase.cs index ebe49f436..520b170f7 100644 --- a/src/TouchSocket.Core/Logger/LoggerBase.cs +++ b/src/TouchSocket.Core/Logger/LoggerBase.cs @@ -20,12 +20,12 @@ namespace TouchSocket.Core public abstract class LoggerBase : ILog { /// - public LogLevel LogLevel { get; set; }= LogLevel.Debug; + public LogLevel LogLevel { get; set; } = LogLevel.Debug; /// public void Log(LogLevel logLevel, object source, string message, Exception exception) { - if (logLevel /// /// - public static void Exception(this ILog logger, object source,string msg, Exception ex) + public static void Exception(this ILog logger, object source, string msg, Exception ex) { logger.Log(LogLevel.Error, source, msg, ex); } diff --git a/src/TouchSocket.Core/Packages_/IPackage.cs b/src/TouchSocket.Core/Packages_/IPackage.cs index 75a950f80..6a06ec5f4 100644 --- a/src/TouchSocket.Core/Packages_/IPackage.cs +++ b/src/TouchSocket.Core/Packages_/IPackage.cs @@ -22,13 +22,13 @@ namespace TouchSocket.Core /// 重写的话,约定基类方法必须先执行 /// /// - void Package(ByteBlock byteBlock); + void Package(in ByteBlock byteBlock); /// /// 解包。 /// 重写的话,约定基类方法必须先执行 /// /// - void Unpackage(ByteBlock byteBlock); + void Unpackage(in ByteBlock byteBlock); } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Packages_/MsgPackage.cs b/src/TouchSocket.Core/Packages_/MsgPackage.cs index 6c08227a9..dd72963b2 100644 --- a/src/TouchSocket.Core/Packages_/MsgPackage.cs +++ b/src/TouchSocket.Core/Packages_/MsgPackage.cs @@ -11,13 +11,13 @@ public string Message { get; set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { byteBlock.Write(this.Message); } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { this.Message = byteBlock.ReadString(); } diff --git a/src/TouchSocket.Core/Packages_/MsgRouterPackage.cs b/src/TouchSocket.Core/Packages_/MsgRouterPackage.cs index fd983b8dd..648cb7de5 100644 --- a/src/TouchSocket.Core/Packages_/MsgRouterPackage.cs +++ b/src/TouchSocket.Core/Packages_/MsgRouterPackage.cs @@ -24,13 +24,13 @@ namespace TouchSocket.Core public string Message { get; set; } /// - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { byteBlock.Write(this.Message); } /// - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { this.Message = byteBlock.ReadString(); } diff --git a/src/TouchSocket.Core/Packages_/PackageBase.cs b/src/TouchSocket.Core/Packages_/PackageBase.cs index 8768ddf79..f4b88dd62 100644 --- a/src/TouchSocket.Core/Packages_/PackageBase.cs +++ b/src/TouchSocket.Core/Packages_/PackageBase.cs @@ -10,18 +10,20 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using System; + namespace TouchSocket.Core { /// /// PackageBase包结构数据。 /// - + [Serializable] public abstract partial class PackageBase : IPackage { /// - public abstract void Package(ByteBlock byteBlock); + public abstract void Package(in ByteBlock byteBlock); /// - public abstract void Unpackage(ByteBlock byteBlock); + public abstract void Unpackage(in ByteBlock byteBlock); } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Packages_/RouterPackage.cs b/src/TouchSocket.Core/Packages_/RouterPackage.cs index 0aad73873..9ce275be7 100644 --- a/src/TouchSocket.Core/Packages_/RouterPackage.cs +++ b/src/TouchSocket.Core/Packages_/RouterPackage.cs @@ -36,7 +36,7 @@ namespace TouchSocket.Core /// 打包所有的路由包信息。顺序为:先调用,然后 /// /// - public sealed override void Package(ByteBlock byteBlock) + public sealed override void Package(in ByteBlock byteBlock) { this.PackageRouter(byteBlock); this.PackageBody(byteBlock); @@ -47,7 +47,7 @@ namespace TouchSocket.Core /// 重写的话,约定基类方法必须先执行 /// /// - public virtual void PackageBody(ByteBlock byteBlock) + public virtual void PackageBody(in ByteBlock byteBlock) { } @@ -56,7 +56,7 @@ namespace TouchSocket.Core /// 重写的话,约定基类方法必须先执行 /// /// - public virtual void PackageRouter(ByteBlock byteBlock) + public virtual void PackageRouter(in ByteBlock byteBlock) { byteBlock.Write(this.Route); byteBlock.Write(this.SourceId); @@ -74,7 +74,7 @@ namespace TouchSocket.Core } /// - public sealed override void Unpackage(ByteBlock byteBlock) + public sealed override void Unpackage(in ByteBlock byteBlock) { this.UnpackageRouter(byteBlock); this.UnpackageBody(byteBlock); @@ -85,7 +85,7 @@ namespace TouchSocket.Core /// 重写的话,约定基类方法必须先执行 /// /// - public virtual void UnpackageBody(ByteBlock byteBlock) + public virtual void UnpackageBody(in ByteBlock byteBlock) { } @@ -94,7 +94,7 @@ namespace TouchSocket.Core /// 重写的话,约定基类方法必须先执行 /// /// - public virtual void UnpackageRouter(ByteBlock byteBlock) + public virtual void UnpackageRouter(in ByteBlock byteBlock) { this.Route = byteBlock.ReadBoolean(); this.SourceId = byteBlock.ReadString(); diff --git a/src/TouchSocket.Core/Packages_/WaitPackage.cs b/src/TouchSocket.Core/Packages_/WaitPackage.cs index d45ff89d2..3cfbd6423 100644 --- a/src/TouchSocket.Core/Packages_/WaitPackage.cs +++ b/src/TouchSocket.Core/Packages_/WaitPackage.cs @@ -34,7 +34,7 @@ namespace TouchSocket.Core public byte Status { get; set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { byteBlock.Write(this.Sign); byteBlock.Write(this.Status); @@ -42,7 +42,7 @@ namespace TouchSocket.Core } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { this.Sign = byteBlock.ReadInt64(); this.Status = (byte)byteBlock.ReadByte(); diff --git a/src/TouchSocket.Core/Packages_/WaitRouterPackage.cs b/src/TouchSocket.Core/Packages_/WaitRouterPackage.cs index 678e3e18d..001dc313c 100644 --- a/src/TouchSocket.Core/Packages_/WaitRouterPackage.cs +++ b/src/TouchSocket.Core/Packages_/WaitRouterPackage.cs @@ -23,20 +23,53 @@ namespace TouchSocket.Core /// public byte Status { get; set; } + /// + /// 是否将等参数放置在Router中。 + /// + protected virtual bool IncludedRouter { get; } + /// - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); - byteBlock.Write(this.Sign); - byteBlock.Write(this.Status); + if (!this.IncludedRouter) + { + byteBlock.Write(this.Sign); + byteBlock.Write(this.Status); + } } /// - public override void UnpackageBody(ByteBlock byteBlock) + public override void PackageRouter(in ByteBlock byteBlock) + { + base.PackageRouter(byteBlock); + if (this.IncludedRouter) + { + byteBlock.Write(this.Sign); + byteBlock.Write(this.Status); + } + } + + /// + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); - this.Sign = byteBlock.ReadInt64(); - this.Status = (byte)byteBlock.ReadByte(); + if (!this.IncludedRouter) + { + this.Sign = byteBlock.ReadInt64(); + this.Status = (byte)byteBlock.ReadByte(); + } + } + + /// + public override void UnpackageRouter(in ByteBlock byteBlock) + { + base.UnpackageRouter(byteBlock); + if (this.IncludedRouter) + { + this.Sign = byteBlock.ReadInt64(); + this.Status = (byte)byteBlock.ReadByte(); + } } } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Plugins/PluginModel.cs b/src/TouchSocket.Core/Plugins/PluginModel.cs index 5466f9b81..8ed48089f 100644 --- a/src/TouchSocket.Core/Plugins/PluginModel.cs +++ b/src/TouchSocket.Core/Plugins/PluginModel.cs @@ -1,7 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace TouchSocket.Core diff --git a/src/TouchSocket.Core/Plugins/PluginsManager.cs b/src/TouchSocket.Core/Plugins/PluginsManager.cs index 5bf0657c5..a886106cb 100644 --- a/src/TouchSocket.Core/Plugins/PluginsManager.cs +++ b/src/TouchSocket.Core/Plugins/PluginsManager.cs @@ -62,7 +62,7 @@ namespace TouchSocket.Core { if (item.GetType().FullName == plugin.GetType().FullName) { - return; + throw new Exception($"{plugin.GetType().FullName}类型的插件为单例类型,且已经注册。"); } } } @@ -105,6 +105,20 @@ namespace TouchSocket.Core object IPluginsManager.Add(Type pluginType) { + if (pluginType.GetCustomAttribute() is PluginOptionAttribute optionAttribute) + { + if (optionAttribute.Singleton) + { + foreach (var item in this.m_plugins) + { + if (item.GetType().FullName == pluginType.FullName) + { + return item; + } + } + } + } + var plugin = (IPlugin)this.m_container.ResolveWithoutRoot(pluginType); ((IPluginsManager)this).Add(plugin); return plugin; diff --git a/src/TouchSocket.Core/Plugins/PluginsManagerExtension.cs b/src/TouchSocket.Core/Plugins/PluginsManagerExtension.cs index 9c3c4eaa8..0688533b9 100644 --- a/src/TouchSocket.Core/Plugins/PluginsManagerExtension.cs +++ b/src/TouchSocket.Core/Plugins/PluginsManagerExtension.cs @@ -86,7 +86,7 @@ namespace TouchSocket.Core /// /// /// - public static void Add(this IPluginsManager pluginsManager, string name, Action action)where T : class + public static void Add(this IPluginsManager pluginsManager, string name, Action action) where T : class { if (typeof(PluginEventArgs).IsAssignableFrom(typeof(T))) { @@ -106,7 +106,7 @@ namespace TouchSocket.Core } pluginsManager.Add(name, newFunc); } - + } /// diff --git a/src/TouchSocket.Core/Pool/ArrayPool.cs b/src/TouchSocket.Core/Pool/ArrayPool.cs index e387aa6f4..34724d184 100644 --- a/src/TouchSocket.Core/Pool/ArrayPool.cs +++ b/src/TouchSocket.Core/Pool/ArrayPool.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; -using System.Text; +using System.IO; using System.Threading; -using System.Threading.Tasks; #if NETCOREAPP3_1_OR_GREATER using System.Numerics; @@ -38,7 +35,7 @@ namespace TouchSocket.Core /// public ArrayPool(int maxArrayLength, int maxArraysPerBucket) { - const int MinimumArrayLength = 16, MaximumArrayLength = 1024 * 1024 * 1024; + const int MinimumArrayLength = 16, MaximumArrayLength = int.MaxValue; if (maxArrayLength > MaximumArrayLength) { maxArrayLength = MaximumArrayLength; @@ -48,16 +45,25 @@ namespace TouchSocket.Core maxArrayLength = MinimumArrayLength; } + var capacity = 0L; var poolId = this.Id; var maxBuckets = SelectBucketIndex(maxArrayLength); var buckets = new Bucket[maxBuckets + 1]; for (var i = 0; i < buckets.Length; i++) { buckets[i] = new Bucket(GetMaxSizeForBucket(i), maxArraysPerBucket, poolId); + long num = GetMaxSizeForBucket(i) * maxArraysPerBucket; + capacity += num; } this.m_buckets = buckets; + this.Capacity = capacity; } + /// + /// 对象池的最大容量。 + /// + public long Capacity { get; private set; } + /// /// 清理池中所有对象。 /// @@ -76,7 +82,7 @@ namespace TouchSocket.Core public long GetPoolSize() { long size = 0; - foreach (var item in m_buckets) + foreach (var item in this.m_buckets) { size += item.Size; } @@ -120,7 +126,7 @@ namespace TouchSocket.Core return buffer; } } - while (++i < this.m_buckets.Length && i != index + MaxBucketsToTry); + while (++i < this.m_buckets.Length && i != index + this.MaxBucketsToTry); buffer = new T[this.m_buckets[index].m_bufferLength]; } @@ -231,7 +237,7 @@ namespace TouchSocket.Core { this.m_lock.Enter(ref lockTaken); - int count = 0; + var count = 0; foreach (var item in this.m_buffers) { if (item != null) diff --git a/src/TouchSocket.Core/Pool/ByteManager/ByteBlock.cs b/src/TouchSocket.Core/Pool/ByteManager/ByteBlock.cs index af2120deb..d648ab09b 100644 --- a/src/TouchSocket.Core/Pool/ByteManager/ByteBlock.cs +++ b/src/TouchSocket.Core/Pool/ByteManager/ByteBlock.cs @@ -523,7 +523,7 @@ namespace TouchSocket.Core if (lend > int.MaxValue) { - lend = Math.Min(need+1024*1024*100, int.MaxValue); + lend = Math.Min(need + 1024 * 1024 * 100, int.MaxValue); } this.SetCapacity((int)lend, true); @@ -668,6 +668,7 @@ namespace TouchSocket.Core } var byteBlock = new ByteBlock(len); byteBlock.Write(this.Buffer, pos, len); + this.m_position += len; return byteBlock; } diff --git a/src/TouchSocket.Core/Pool/ByteManager/BytePool.cs b/src/TouchSocket.Core/Pool/ByteManager/BytePool.cs index c0c9ca138..c9ffd2661 100644 --- a/src/TouchSocket.Core/Pool/ByteManager/BytePool.cs +++ b/src/TouchSocket.Core/Pool/ByteManager/BytePool.cs @@ -23,13 +23,13 @@ namespace TouchSocket.Core static BytePool() { - Default = new BytePool(); + Default=new BytePool(); } /// /// 内存池 /// - public BytePool() : this(1024 * 1024 * 20, 100) + public BytePool() : this(1024 * 1024 * 10, 100) { } @@ -51,7 +51,16 @@ namespace TouchSocket.Core /// /// 默认的内存池实例 /// - public static BytePool Default { get; } + public static BytePool Default { get; private set; } + + /// + /// 设置默认内存池实例。 + /// + /// + public static void SetDefault(BytePool bytePool) + { + Default = bytePool; + } /// /// 回收内存时,自动归零 diff --git a/src/TouchSocket.Core/Reflection/DynamicMethodMemberAccessor.cs b/src/TouchSocket.Core/Reflection/DynamicMethodMemberAccessor.cs index 9eea1c00c..f355e93de 100644 --- a/src/TouchSocket.Core/Reflection/DynamicMethodMemberAccessor.cs +++ b/src/TouchSocket.Core/Reflection/DynamicMethodMemberAccessor.cs @@ -11,17 +11,15 @@ namespace TouchSocket.Core { private readonly ConcurrentDictionary m_classAccessors = new ConcurrentDictionary(); - private static DynamicMethodMemberAccessor m_default; - static DynamicMethodMemberAccessor() { - m_default = new DynamicMethodMemberAccessor(); + Default = new DynamicMethodMemberAccessor(); } /// /// DynamicMethodMemberAccessor的默认实例。 /// - public static DynamicMethodMemberAccessor Default { get => m_default; } + public static DynamicMethodMemberAccessor Default { get; private set; } /// /// 获取字段 @@ -62,7 +60,7 @@ namespace TouchSocket.Core } memberAccessor.Build(); classAccessor = memberAccessor; - m_classAccessors.TryAdd(typekey, classAccessor); + this.m_classAccessors.TryAdd(typekey, classAccessor); } return classAccessor; } diff --git a/src/TouchSocket.Core/Reflection/InstanceCreater.cs b/src/TouchSocket.Core/Reflection/InstanceCreater.cs index ffcbb58d0..b71baf858 100644 --- a/src/TouchSocket.Core/Reflection/InstanceCreater.cs +++ b/src/TouchSocket.Core/Reflection/InstanceCreater.cs @@ -1,10 +1,6 @@ using System; using System.Collections; -using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; -using System.Text; -using System.Threading.Tasks; namespace TouchSocket.Core { diff --git a/src/TouchSocket.Core/Reflection/MemberAccessor.cs b/src/TouchSocket.Core/Reflection/MemberAccessor.cs index 373e76f75..32a4b128f 100644 --- a/src/TouchSocket.Core/Reflection/MemberAccessor.cs +++ b/src/TouchSocket.Core/Reflection/MemberAccessor.cs @@ -118,7 +118,7 @@ namespace TouchSocket.Core catch { } - + } foreach (var propertyInfo in this.OnGetProperties.Invoke(this.Type)) { diff --git a/src/TouchSocket.Core/Reflection/Method.cs b/src/TouchSocket.Core/Reflection/Method.cs index 583fa12d1..0bbdb322e 100644 --- a/src/TouchSocket.Core/Reflection/Method.cs +++ b/src/TouchSocket.Core/Reflection/Method.cs @@ -45,13 +45,6 @@ namespace TouchSocket.Core /// public class Method { - /// - /// FastInvokeHandler - /// - /// - /// - /// - public delegate object FastInvokeHandler(object target, object[] paramters); /// /// 方法执行委托 /// @@ -106,6 +99,14 @@ namespace TouchSocket.Core } } + /// + /// FastInvokeHandler + /// + /// + /// + /// + public delegate object FastInvokeHandler(object target, object[] paramters); + /// /// 是否具有返回值。当返回值为Task时,也会认为没有返回值。 /// @@ -327,6 +328,144 @@ namespace TouchSocket.Core } } + private static void EmitBoxIfNeeded(ILGenerator il, System.Type type) + { + if (type.IsValueType) + { + il.Emit(OpCodes.Box, type); + } + } + + private static void EmitCastToReference(ILGenerator il, System.Type type) + { + if (type.IsValueType) + { + il.Emit(OpCodes.Unbox_Any, type); + } + else + { + il.Emit(OpCodes.Castclass, type); + } + } + + private static void EmitFastInt(ILGenerator il, int value) + { + switch (value) + { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + { + il.Emit(OpCodes.Ldc_I4_S, (SByte)value); + } + else + { + il.Emit(OpCodes.Ldc_I4, value); + } + } + + private static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo) + { + var dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) + }, methodInfo.DeclaringType.Module); + var il = dynamicMethod.GetILGenerator(); + var ps = methodInfo.GetParameters(); + var paramTypes = new Type[ps.Length]; + for (var i = 0; i < paramTypes.Length; i++) + { + paramTypes[i] = ps[i].ParameterType.IsByRef ? ps[i].ParameterType.GetElementType() : ps[i].ParameterType; + } + var locals = new LocalBuilder[paramTypes.Length]; + + for (var i = 0; i < paramTypes.Length; i++) + { + locals[i] = il.DeclareLocal(paramTypes[i], true); + } + for (var i = 0; i < paramTypes.Length; i++) + { + il.Emit(OpCodes.Ldarg_1); + EmitFastInt(il, i); + il.Emit(OpCodes.Ldelem_Ref); + EmitCastToReference(il, paramTypes[i]); + il.Emit(OpCodes.Stloc, locals[i]); + } + if (!methodInfo.IsStatic) + { + il.Emit(OpCodes.Ldarg_0); + } + for (var i = 0; i < paramTypes.Length; i++) + { + if (ps[i].ParameterType.IsByRef) + il.Emit(OpCodes.Ldloca_S, locals[i]); + else + il.Emit(OpCodes.Ldloc, locals[i]); + } + if (methodInfo.IsStatic) + il.EmitCall(OpCodes.Call, methodInfo, null); + else + il.EmitCall(OpCodes.Callvirt, methodInfo, null); + if (methodInfo.ReturnType == typeof(void)) + il.Emit(OpCodes.Ldnull); + else + EmitBoxIfNeeded(il, methodInfo.ReturnType); + + for (var i = 0; i < paramTypes.Length; i++) + { + if (ps[i].ParameterType.IsByRef) + { + il.Emit(OpCodes.Ldarg_1); + EmitFastInt(il, i); + il.Emit(OpCodes.Ldloc, locals[i]); + if (locals[i].LocalType.IsValueType) + il.Emit(OpCodes.Box, locals[i].LocalType); + il.Emit(OpCodes.Stelem_Ref); + } + } + + il.Emit(OpCodes.Ret); + var invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler)); + return invoder; + } + /// /// 生成方法的调用委托 /// @@ -382,135 +521,5 @@ namespace TouchSocket.Core return Expression.Lambda>(bodyCast, instance, parameters).Compile(); } } - - private static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo) - { - var dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) - }, methodInfo.DeclaringType.Module); - var il = dynamicMethod.GetILGenerator(); - var ps = methodInfo.GetParameters(); - var paramTypes = new Type[ps.Length]; - for (var i = 0; i < paramTypes.Length; i++) - { - paramTypes[i] = ps[i].ParameterType.IsByRef ? ps[i].ParameterType.GetElementType() : ps[i].ParameterType; - - } - var locals = new LocalBuilder[paramTypes.Length]; - - for (var i = 0; i < paramTypes.Length; i++) - { - locals[i] = il.DeclareLocal(paramTypes[i], true); - } - for (var i = 0; i < paramTypes.Length; i++) - { - il.Emit(OpCodes.Ldarg_1); - EmitFastInt(il, i); - il.Emit(OpCodes.Ldelem_Ref); - EmitCastToReference(il, paramTypes[i]); - il.Emit(OpCodes.Stloc, locals[i]); - } - if (!methodInfo.IsStatic) - { - il.Emit(OpCodes.Ldarg_0); - } - for (var i = 0; i < paramTypes.Length; i++) - { - if (ps[i].ParameterType.IsByRef) - il.Emit(OpCodes.Ldloca_S, locals[i]); - else - il.Emit(OpCodes.Ldloc, locals[i]); - } - if (methodInfo.IsStatic) - il.EmitCall(OpCodes.Call, methodInfo, null); - else - il.EmitCall(OpCodes.Callvirt, methodInfo, null); - if (methodInfo.ReturnType == typeof(void)) - il.Emit(OpCodes.Ldnull); - else - EmitBoxIfNeeded(il, methodInfo.ReturnType); - - for (var i = 0; i < paramTypes.Length; i++) - { - if (ps[i].ParameterType.IsByRef) - { - il.Emit(OpCodes.Ldarg_1); - EmitFastInt(il, i); - il.Emit(OpCodes.Ldloc, locals[i]); - if (locals[i].LocalType.IsValueType) - il.Emit(OpCodes.Box, locals[i].LocalType); - il.Emit(OpCodes.Stelem_Ref); - } - } - - il.Emit(OpCodes.Ret); - var invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler)); - return invoder; - } - - private static void EmitCastToReference(ILGenerator il, System.Type type) - { - if (type.IsValueType) - { - il.Emit(OpCodes.Unbox_Any, type); - } - else - { - il.Emit(OpCodes.Castclass, type); - } - } - - private static void EmitBoxIfNeeded(ILGenerator il, System.Type type) - { - if (type.IsValueType) - { - il.Emit(OpCodes.Box, type); - } - } - - private static void EmitFastInt(ILGenerator il, int value) - { - switch (value) - { - case -1: - il.Emit(OpCodes.Ldc_I4_M1); - return; - case 0: - il.Emit(OpCodes.Ldc_I4_0); - return; - case 1: - il.Emit(OpCodes.Ldc_I4_1); - return; - case 2: - il.Emit(OpCodes.Ldc_I4_2); - return; - case 3: - il.Emit(OpCodes.Ldc_I4_3); - return; - case 4: - il.Emit(OpCodes.Ldc_I4_4); - return; - case 5: - il.Emit(OpCodes.Ldc_I4_5); - return; - case 6: - il.Emit(OpCodes.Ldc_I4_6); - return; - case 7: - il.Emit(OpCodes.Ldc_I4_7); - return; - case 8: - il.Emit(OpCodes.Ldc_I4_8); - return; - } - - if (value > -129 && value < 128) - { - il.Emit(OpCodes.Ldc_I4_S, (SByte)value); - } - else - { - il.Emit(OpCodes.Ldc_I4, value); - } - } } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Run/Action/EasyTask.cs b/src/TouchSocket.Core/Run/Action/EasyTask.cs index 2dd64001c..bbbf40bf0 100644 --- a/src/TouchSocket.Core/Run/Action/EasyTask.cs +++ b/src/TouchSocket.Core/Run/Action/EasyTask.cs @@ -10,9 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System; -using System.Collections.Concurrent; -using System.Threading; using System.Threading.Tasks; namespace TouchSocket.Core @@ -27,7 +24,7 @@ namespace TouchSocket.Core InitCompletedTask(); } - + /// /// 已完成的Task /// diff --git a/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs b/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs index d57b18bd4..b61b0edc2 100644 --- a/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs +++ b/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs @@ -63,7 +63,7 @@ namespace TouchSocket.Core /// /// 流 /// 对象 - public static void Serialize(ByteBlock byteBlock, T graph) + public static void Serialize(ByteBlock byteBlock, in T graph) { byteBlock.Pos = 1; SerializeObject(byteBlock, graph); @@ -113,7 +113,7 @@ namespace TouchSocket.Core return len; } - private static int SerializeDictionary(ByteBlock stream, IEnumerable param) + private static int SerializeDictionary(in ByteBlock stream, in IEnumerable param) { var len = 0; if (param != null) @@ -123,12 +123,14 @@ namespace TouchSocket.Core len += 4; uint paramLen = 0; +#pragma warning disable IDE0007 // 使用隐式类型 foreach (dynamic item in param) { len += SerializeObject(stream, item.Key); len += SerializeObject(stream, item.Value); paramLen++; } +#pragma warning restore IDE0007 // 使用隐式类型 var newPosition = stream.Pos; stream.Pos = oldPosition; stream.Write(TouchSocketBitConverter.Default.GetBytes(paramLen)); @@ -137,7 +139,7 @@ namespace TouchSocket.Core return len; } - private static int SerializeIListOrArray(ByteBlock stream, IEnumerable param) + private static int SerializeIListOrArray(in ByteBlock stream, in IEnumerable param) { var len = 0; if (param != null) @@ -160,7 +162,7 @@ namespace TouchSocket.Core return len; } - private static int SerializeObject(ByteBlock byteBlock, T graph) + private static int SerializeObject(in ByteBlock byteBlock, in T graph) { var len = 0; byte[] data = null; @@ -264,11 +266,21 @@ namespace TouchSocket.Core } else { - data = enumValType == TouchSocketCoreUtility.shortType - ? TouchSocketBitConverter.Default.GetBytes(Convert.ToInt16(graph)) - : enumValType == TouchSocketCoreUtility.intType - ? TouchSocketBitConverter.Default.GetBytes(Convert.ToInt32(graph)) - : TouchSocketBitConverter.Default.GetBytes(Convert.ToInt64(graph)); + if (enumValType == TouchSocketCoreUtility.shortType) + { + data = TouchSocketBitConverter.Default.GetBytes(Convert.ToInt16(graph)); + } + else + { + if (enumValType == TouchSocketCoreUtility.intType) + { + data = TouchSocketBitConverter.Default.GetBytes(Convert.ToInt32(graph)); + } + else + { + data = TouchSocketBitConverter.Default.GetBytes(Convert.ToInt64(graph)); + } + } } break; } diff --git a/src/TouchSocket.Core/Serialization/SerializeConvert.cs b/src/TouchSocket.Core/Serialization/SerializeConvert.cs index f38dc2a9d..498118d4f 100644 --- a/src/TouchSocket.Core/Serialization/SerializeConvert.cs +++ b/src/TouchSocket.Core/Serialization/SerializeConvert.cs @@ -34,7 +34,7 @@ namespace TouchSocket.Core /// /// 数据对象 /// - public static byte[] BinarySerialize(object obj) + public static byte[] BinarySerialize(in object obj) { using (var serializeStream = new MemoryStream()) { @@ -49,7 +49,7 @@ namespace TouchSocket.Core /// /// 数据对象 /// 路径 - public static void BinarySerializeToFile(object obj, string path) + public static void BinarySerializeToFile(in object obj, string path) { using (var serializeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { @@ -64,7 +64,7 @@ namespace TouchSocket.Core /// /// /// - public static void BinarySerialize(Stream stream, object obj) + public static void BinarySerialize(Stream stream, in object obj) { var bf = new BinaryFormatter(); bf.Serialize(stream, obj); @@ -186,7 +186,7 @@ namespace TouchSocket.Core /// /// /// - public static void FastBinarySerialize(ByteBlock stream, T obj) + public static void FastBinarySerialize(ByteBlock stream,in T obj) { FastBinaryFormatter.Serialize(stream, obj); } @@ -196,7 +196,7 @@ namespace TouchSocket.Core /// /// /// - public static byte[] FastBinarySerialize(T obj) + public static byte[] FastBinarySerialize(in T obj) { using (var byteBlock = new ByteBlock()) { @@ -398,7 +398,7 @@ namespace TouchSocket.Core } #if NETCOREAPP3_1_OR_GREATER - return System.Text.Json.JsonSerializer.Serialize(item); + return System.Text.Json.JsonSerializer.Serialize(item); #else return Newtonsoft.Json.JsonConvert.SerializeObject(item); #endif @@ -418,7 +418,7 @@ namespace TouchSocket.Core } #if NETCOREAPP3_1_OR_GREATER - return System.Text.Json.JsonSerializer.Deserialize(json,type); + return System.Text.Json.JsonSerializer.Deserialize(json, type); #else return Newtonsoft.Json.JsonConvert.DeserializeObject(json, type); #endif diff --git a/src/TouchSocket.Core/TouchSocket.Core.csproj b/src/TouchSocket.Core/TouchSocket.Core.csproj index 89eb65fdf..4eecb0698 100644 --- a/src/TouchSocket.Core/TouchSocket.Core.csproj +++ b/src/TouchSocket.Core/TouchSocket.Core.csproj @@ -1,45 +1,14 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 message;arraypool;logger;plugin;3DES;xml;filepool;serialize 这是为TouchSocket系提供基础服务功能的库,其中包含:内存池、对象池、等待逻辑池、AppMessenger、3DES加密、Xml快速存储、运行时间测量器、文件快捷操作、高性能序列化器、规范日志接口等。 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt TouchSocket.Core - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.Core + ..\..\Build\NugetPackages\TouchSocket.Core - - - True - - - - True - - - - @@ -54,4 +23,14 @@ + + + True + Embedded + True + + + + true + diff --git a/src/TouchSocket.Core/WaitPool/IWaitData.cs b/src/TouchSocket.Core/WaitPool/IWaitData.cs index 91a4d54fe..0bf7ec48e 100644 --- a/src/TouchSocket.Core/WaitPool/IWaitData.cs +++ b/src/TouchSocket.Core/WaitPool/IWaitData.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; namespace TouchSocket.Core { diff --git a/src/TouchSocket.Core/WaitPool/WaitData.cs b/src/TouchSocket.Core/WaitPool/WaitData.cs index 100d39739..545ad3872 100644 --- a/src/TouchSocket.Core/WaitPool/WaitData.cs +++ b/src/TouchSocket.Core/WaitPool/WaitData.cs @@ -23,7 +23,6 @@ namespace TouchSocket.Core { private readonly AutoResetEvent m_waitHandle; private volatile WaitDataStatus m_status; - private T m_waitResult; /// /// WaitData @@ -34,10 +33,10 @@ namespace TouchSocket.Core } /// - public WaitDataStatus Status { get => m_status; } + public WaitDataStatus Status { get => this.m_status; } /// - public T WaitResult { get => m_waitResult; } + public T WaitResult { get; private set; } /// public void Cancel() @@ -50,7 +49,7 @@ namespace TouchSocket.Core public void Reset() { this.m_status = WaitDataStatus.Default; - this.m_waitResult = default; + this.WaitResult = default; this.m_waitHandle.Reset(); } @@ -64,7 +63,7 @@ namespace TouchSocket.Core /// public bool Set(T waitResult) { - this.m_waitResult = waitResult; + this.WaitResult = waitResult; this.m_status = WaitDataStatus.SetRunning; return this.m_waitHandle.Set(); } @@ -81,7 +80,7 @@ namespace TouchSocket.Core /// public void SetResult(T result) { - this.m_waitResult = result; + this.WaitResult = result; } /// @@ -110,7 +109,7 @@ namespace TouchSocket.Core protected override void Dispose(bool disposing) { this.m_status = WaitDataStatus.Disposed; - this.m_waitResult = default; + this.WaitResult = default; this.m_waitHandle.SafeDispose(); base.Dispose(disposing); } diff --git a/src/TouchSocket.Core/WaitPool/WaitDataAsync.cs b/src/TouchSocket.Core/WaitPool/WaitDataAsync.cs index 11043ead9..9e1546429 100644 --- a/src/TouchSocket.Core/WaitPool/WaitDataAsync.cs +++ b/src/TouchSocket.Core/WaitPool/WaitDataAsync.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -15,7 +12,6 @@ namespace TouchSocket.Core { private readonly AsyncAutoResetEvent m_asyncWaitHandle; private volatile WaitDataStatus m_status; - private T m_waitResult; /// /// 构造函数 @@ -26,10 +22,10 @@ namespace TouchSocket.Core } /// - public WaitDataStatus Status { get => m_status; } + public WaitDataStatus Status { get => this.m_status; } /// - public T WaitResult { get => m_waitResult; } + public T WaitResult { get; private set; } /// public void Cancel() @@ -42,7 +38,7 @@ namespace TouchSocket.Core public void Reset() { this.m_status = WaitDataStatus.Default; - this.m_waitResult = default; + this.WaitResult = default; this.m_asyncWaitHandle.Reset(); } @@ -56,7 +52,7 @@ namespace TouchSocket.Core /// public bool Set(T waitResult) { - this.m_waitResult = waitResult; + this.WaitResult = waitResult; this.m_status = WaitDataStatus.SetRunning; return this.m_asyncWaitHandle.Set(); } @@ -73,10 +69,10 @@ namespace TouchSocket.Core /// public void SetResult(T result) { - this.m_waitResult = result; + this.WaitResult = result; } - + /// /// 等待指定时间 /// @@ -105,7 +101,7 @@ namespace TouchSocket.Core protected override void Dispose(bool disposing) { this.m_status = WaitDataStatus.Disposed; - this.m_waitResult = default; + this.WaitResult = default; this.m_asyncWaitHandle.SafeDispose(); base.Dispose(disposing); } diff --git a/src/TouchSocket.Core/WaitPool/WaitHandlePool.cs b/src/TouchSocket.Core/WaitPool/WaitHandlePool.cs index 933624977..6cb79f904 100644 --- a/src/TouchSocket.Core/WaitPool/WaitHandlePool.cs +++ b/src/TouchSocket.Core/WaitPool/WaitHandlePool.cs @@ -64,7 +64,7 @@ namespace TouchSocket.Core /// public void Destroy(WaitData waitData) { - if (waitData.WaitResult==null) + if (waitData.WaitResult == null) { return; } diff --git a/src/TouchSocket.Dmtp/Actor/DmtpActor.cs b/src/TouchSocket.Dmtp/Actor/DmtpActor.cs index aaa4daa5e..a8845cc46 100644 --- a/src/TouchSocket.Dmtp/Actor/DmtpActor.cs +++ b/src/TouchSocket.Dmtp/Actor/DmtpActor.cs @@ -83,16 +83,31 @@ namespace TouchSocket.Dmtp /// public WaitHandlePool WaitHandlePool { get; private set; } + /// + public bool IsReliable { get; } + #endregion 属性 /// - /// 构造函数 + /// 创建一个Dmtp协议的最基础功能件 /// - public DmtpActor(bool allowRoute) + /// 是否允许路由 + /// 是不是基于可靠协议运行的 + public DmtpActor(bool allowRoute,bool isReliable) { this.WaitHandlePool = new WaitHandlePool(); this.AllowRoute = allowRoute; this.LastActiveTime = DateTime.Now; + this.IsReliable = isReliable; + } + + /// + /// 创建一个可靠协议的Dmtp协议的最基础功能件 + /// + /// + public DmtpActor(bool allowRoute):this(allowRoute,true) + { + } /// @@ -639,7 +654,7 @@ namespace TouchSocket.Dmtp } default: { - if (message.ProtocolFlags<20) + if (message.ProtocolFlags < 20) { return true; } diff --git a/src/TouchSocket.Dmtp/Actor/IDmtpActor.cs b/src/TouchSocket.Dmtp/Actor/IDmtpActor.cs index 657328549..47979962a 100644 --- a/src/TouchSocket.Dmtp/Actor/IDmtpActor.cs +++ b/src/TouchSocket.Dmtp/Actor/IDmtpActor.cs @@ -16,6 +16,11 @@ namespace TouchSocket.Dmtp /// bool AllowRoute { get; } + /// + /// 是否基于可靠协议构建。例如:基于Tcp则为,基于Udp则为。 + /// + bool IsReliable { get;} + /// /// 包含当前功能件的宿主通讯端。 /// diff --git a/src/TouchSocket.Dmtp/Channel/ChannelPackage.cs b/src/TouchSocket.Dmtp/Channel/ChannelPackage.cs index 743632796..5e090507e 100644 --- a/src/TouchSocket.Dmtp/Channel/ChannelPackage.cs +++ b/src/TouchSocket.Dmtp/Channel/ChannelPackage.cs @@ -10,7 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System; using TouchSocket.Core; namespace TouchSocket.Dmtp @@ -39,17 +38,17 @@ namespace TouchSocket.Dmtp return this.Data == null ? 1024 : this.Data.Len + 1024; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write(this.RunNow); byteBlock.Write((byte)this.DataType); byteBlock.Write(this.ChannelId); - + byteBlock.WriteByteBlock(this.Data); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.RunNow = byteBlock.ReadBoolean(); diff --git a/src/TouchSocket.Dmtp/Channel/DmtpChannelExtension.cs b/src/TouchSocket.Dmtp/Channel/DmtpChannelExtension.cs index e32d4fe65..35a7fa1b1 100644 --- a/src/TouchSocket.Dmtp/Channel/DmtpChannelExtension.cs +++ b/src/TouchSocket.Dmtp/Channel/DmtpChannelExtension.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; namespace TouchSocket.Dmtp { diff --git a/src/TouchSocket.Dmtp/Channel/IDmtpChannelAsync.cs b/src/TouchSocket.Dmtp/Channel/IDmtpChannelAsync.cs index a41a5ea2f..22e46a563 100644 --- a/src/TouchSocket.Dmtp/Channel/IDmtpChannelAsync.cs +++ b/src/TouchSocket.Dmtp/Channel/IDmtpChannelAsync.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; using TouchSocket.Core; namespace TouchSocket.Dmtp diff --git a/src/TouchSocket.Dmtp/Channel/InternalChannelAsync.cs b/src/TouchSocket.Dmtp/Channel/InternalChannelAsync.cs index b05ebc0c4..a4242ecb0 100644 --- a/src/TouchSocket.Dmtp/Channel/InternalChannelAsync.cs +++ b/src/TouchSocket.Dmtp/Channel/InternalChannelAsync.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Collections.Generic; using System.Threading; -using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Dmtp diff --git a/src/TouchSocket.Dmtp/Channel/WaitCreateChannelPackage.cs b/src/TouchSocket.Dmtp/Channel/WaitCreateChannelPackage.cs index 0080c1cf4..4116e1fcd 100644 --- a/src/TouchSocket.Dmtp/Channel/WaitCreateChannelPackage.cs +++ b/src/TouchSocket.Dmtp/Channel/WaitCreateChannelPackage.cs @@ -34,7 +34,7 @@ namespace TouchSocket.Dmtp /// public bool Random { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write(this.Random); @@ -42,7 +42,7 @@ namespace TouchSocket.Dmtp byteBlock.WritePackage(this.Metadata); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.Random = byteBlock.ReadBoolean(); diff --git a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpClient.cs b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpClient.cs index d56ae24bf..303e2ddf2 100644 --- a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpClient.cs +++ b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpClient.cs @@ -62,12 +62,12 @@ namespace TouchSocket.Dmtp request.AsMethod(DmtpUtility.Dmtp); var response = this.RequestContent(request); - if (response.StatusCode == "101") + if (response.StatusCode == 101) { this.SwitchProtocolToDmtp(); this.m_smtpActor.Handshake(this.Config.GetValue(DmtpConfigExtension.VerifyTokenProperty), this.Config.GetValue(DmtpConfigExtension.DefaultIdProperty), - timeout, this.Config.GetValue(DmtpConfigExtension.MetadataProperty),CancellationToken.None); + timeout, this.Config.GetValue(DmtpConfigExtension.MetadataProperty), CancellationToken.None); return this; } else diff --git a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpService.cs b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpService.cs index fddf13388..7ba090302 100644 --- a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpService.cs +++ b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpService.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; -using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Http; using TouchSocket.Sockets; diff --git a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpSocketClient.cs b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpSocketClient.cs index 3e2af4a55..1d2f52cda 100644 --- a/src/TouchSocket.Dmtp/Components/Http/HttpDmtpSocketClient.cs +++ b/src/TouchSocket.Dmtp/Components/Http/HttpDmtpSocketClient.cs @@ -133,7 +133,7 @@ namespace TouchSocket.Dmtp request.SafeDispose(); this.SetRpcActor(this.m_internalOnRpcActorInit.Invoke()); - this.DefaultSend(new HttpResponse().SetStatus("101", "Switching Protocols").BuildAsBytes()); + this.DefaultSend(new HttpResponse().SetStatus(101, "Switching Protocols").BuildAsBytes()); return; } base.OnReceivedHttpRequest(request); diff --git a/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpService.cs b/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpService.cs index 55ed3f7e1..b71ea62c5 100644 --- a/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpService.cs +++ b/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpService.cs @@ -10,7 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.Threading.Tasks; using TouchSocket.Http; namespace TouchSocket.Dmtp diff --git a/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpSocketClient.cs b/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpSocketClient.cs index 8103cf947..61955c3ff 100644 --- a/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpSocketClient.cs +++ b/src/TouchSocket.Dmtp/Components/Http/Interface/IHttpDmtpSocketClient.cs @@ -11,12 +11,14 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using TouchSocket.Sockets; + namespace TouchSocket.Dmtp { /// /// IHttpDmtpSocketClient /// - public interface IHttpDmtpSocketClient : IHttpDmtpClientBase + public interface IHttpDmtpSocketClient : IHttpDmtpClientBase, ISocketClient { } diff --git a/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpService.cs b/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpService.cs index 1ddc46aee..f5c25e89f 100644 --- a/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpService.cs +++ b/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpService.cs @@ -17,7 +17,7 @@ namespace TouchSocket.Dmtp /// /// ITcpDmtpService /// - public interface ITcpDmtpService : ITcpService,IDmtpService + public interface ITcpDmtpService : ITcpService, IDmtpService { } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpSocketClient.cs b/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpSocketClient.cs index d1f8c9643..cba452aad 100644 --- a/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpSocketClient.cs +++ b/src/TouchSocket.Dmtp/Components/TCP/Interface/ITcpDmtpSocketClient.cs @@ -11,13 +11,15 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using TouchSocket.Sockets; + namespace TouchSocket.Dmtp { /// /// ITcpDmtpSocketClient /// - public interface ITcpDmtpSocketClient : ITcpDmtpClientBase + public interface ITcpDmtpSocketClient : ITcpDmtpClientBase, ISocketClient { } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClient.cs b/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClient.cs index 33846bb44..4ff80cc3a 100644 --- a/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClient.cs +++ b/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClient.cs @@ -15,9 +15,9 @@ using System.Threading.Tasks; namespace TouchSocket.Dmtp { /// - /// IWebsocketDmtpClient + /// IWebSocketDmtpClient /// - public interface IWebsocketDmtpClient : IWebsocketDmtpClientBase + public interface IWebSocketDmtpClient : IWebSocketDmtpClientBase { /// /// 异步连接 diff --git a/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClientBase.cs b/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClientBase.cs index 3ecba66cf..48b1cbf7c 100644 --- a/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClientBase.cs +++ b/src/TouchSocket.Dmtp/Components/Websocket/Interface/IWebsocketDmtpClientBase.cs @@ -4,9 +4,9 @@ using TouchSocket.Sockets; namespace TouchSocket.Dmtp { /// - /// IWebsocketDmtpClientBase + /// IWebSocketDmtpClientBase /// - public interface IWebsocketDmtpClientBase : IClient, IPluginObject, IDmtpActorObject + public interface IWebSocketDmtpClientBase : IClient, IPluginObject, IDmtpActorObject { /// /// 客户端的Id diff --git a/src/TouchSocket.Dmtp/Components/Websocket/WebsocketDmtpClient.cs b/src/TouchSocket.Dmtp/Components/Websocket/WebsocketDmtpClient.cs index e92507a16..ab78191bd 100644 --- a/src/TouchSocket.Dmtp/Components/Websocket/WebsocketDmtpClient.cs +++ b/src/TouchSocket.Dmtp/Components/Websocket/WebsocketDmtpClient.cs @@ -20,9 +20,9 @@ using TouchSocket.Sockets; namespace TouchSocket.Dmtp { /// - /// WebsocketDmtpClient + /// WebSocketDmtpClient /// - public class WebsocketDmtpClient : BaseSocket, IWebsocketDmtpClient + public class WebSocketDmtpClient : BaseSocket, IWebSocketDmtpClient { #region 字段 @@ -49,7 +49,7 @@ namespace TouchSocket.Dmtp /// /// 断开连接 /// - public DisconnectEventHandler Disconnected { get; set; } + public DisconnectEventHandler Disconnected { get; set; } /// public string Id => this.DmtpActor.Id; @@ -69,7 +69,7 @@ namespace TouchSocket.Dmtp public Func OnHandleReceivedData { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public Protocol Protocol { get; set; } = DmtpUtility.DmtpProtocol; - public DateTime LastReceivedTime { get;private set; } + public DateTime LastReceivedTime { get; private set; } public DateTime LastSendTime { get; private set; } @@ -91,7 +91,7 @@ namespace TouchSocket.Dmtp { return; } - m_cancellationTokenSource = new CancellationTokenSource(); + this.m_cancellationTokenSource = new CancellationTokenSource(); if (this.m_client == null || this.m_client.State != WebSocketState.Open) { this.m_client.SafeDispose(); @@ -115,7 +115,7 @@ namespace TouchSocket.Dmtp { ReceivedCallBack = PrivateHandleReceivedData }; - _=this.BeginReceive(); + _ = this.BeginReceive(); } this.m_smtpActor.Handshake(this.Config.GetValue(DmtpConfigExtension.VerifyTokenProperty), @@ -147,7 +147,7 @@ namespace TouchSocket.Dmtp /// /// /// - public IWebsocketDmtpClient Setup(string ipHost) + public IWebSocketDmtpClient Setup(string ipHost) { var config = new TouchSocketConfig(); config.SetRemoteIPHost(new IPHost(ipHost)); @@ -159,7 +159,7 @@ namespace TouchSocket.Dmtp /// /// /// - public IWebsocketDmtpClient Setup(TouchSocketConfig config) + public IWebSocketDmtpClient Setup(TouchSocketConfig config) { if (config == null) { @@ -216,7 +216,7 @@ namespace TouchSocket.Dmtp /// protected virtual void OnDisconnected(DisconnectEventArgs e) { - if (this.PluginsManager.Raise(nameof(ITcpDisconnectedPlguin.OnTcpDisconnected), this, e)) + if (this.PluginsManager.Raise(nameof(ITcpDisconnectedPlugin.OnTcpDisconnected), this, e)) { return; } @@ -258,7 +258,7 @@ namespace TouchSocket.Dmtp if (this.IsHandshaked) { this.IsHandshaked = false; - m_cancellationTokenSource?.Cancel(); + this.m_cancellationTokenSource?.Cancel(); this.m_client.CloseAsync(WebSocketCloseStatus.NormalClosure, msg, CancellationToken.None); this.m_client.SafeDispose(); this.DmtpActor.SafeDispose(); diff --git a/src/TouchSocket.Dmtp/Enum/RouteType.cs b/src/TouchSocket.Dmtp/Enum/RouteType.cs index 3074f2594..169ec2e95 100644 --- a/src/TouchSocket.Dmtp/Enum/RouteType.cs +++ b/src/TouchSocket.Dmtp/Enum/RouteType.cs @@ -85,7 +85,7 @@ namespace TouchSocket.Dmtp /// /// 一个Ping探测路由包 /// - public static readonly RouteType Ping = new RouteType("Ping"); + public static readonly RouteType Ping = new RouteType("Ping"); /// /// 创建通道路由包。 diff --git a/src/TouchSocket.Dmtp/EventArgs/DmtpVerifyEventArgs.cs b/src/TouchSocket.Dmtp/EventArgs/DmtpVerifyEventArgs.cs index ae39ad14e..05709f4e9 100644 --- a/src/TouchSocket.Dmtp/EventArgs/DmtpVerifyEventArgs.cs +++ b/src/TouchSocket.Dmtp/EventArgs/DmtpVerifyEventArgs.cs @@ -12,7 +12,6 @@ //------------------------------------------------------------------------------ using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Dmtp { diff --git a/src/TouchSocket.Dmtp/Extensions/DmtpActorExtension.cs b/src/TouchSocket.Dmtp/Extensions/DmtpActorExtension.cs index 31d05ed67..49b209d12 100644 --- a/src/TouchSocket.Dmtp/Extensions/DmtpActorExtension.cs +++ b/src/TouchSocket.Dmtp/Extensions/DmtpActorExtension.cs @@ -50,17 +50,17 @@ namespace TouchSocket.Dmtp public static IDmtpChannel CreateChannel(this IDmtpActorObject client, int id, Metadata metadata = default) { - return client.DmtpActor.CreateChannel(id,metadata); + return client.DmtpActor.CreateChannel(id, metadata); } public static IDmtpChannel CreateChannel(this IDmtpActorObject client, string targetId, int id, Metadata metadata = default) { - return client.DmtpActor.CreateChannel(targetId, id,metadata); + return client.DmtpActor.CreateChannel(targetId, id, metadata); } public static IDmtpChannel CreateChannel(this IDmtpActorObject client, string targetId, Metadata metadata = default) { - return client.DmtpActor.CreateChannel(targetId,metadata); + return client.DmtpActor.CreateChannel(targetId, metadata); } public static Task CreateChannelAsync(this IDmtpActorObject client, Metadata metadata = default) @@ -70,17 +70,17 @@ namespace TouchSocket.Dmtp public static Task CreateChannelAsync(this IDmtpActorObject client, int id, Metadata metadata = default) { - return client.DmtpActor.CreateChannelAsync(id,metadata); + return client.DmtpActor.CreateChannelAsync(id, metadata); } public static Task CreateChannelAsync(this IDmtpActorObject client, string targetId, int id, Metadata metadata = default) { - return client.DmtpActor.CreateChannelAsync(targetId, id,metadata); + return client.DmtpActor.CreateChannelAsync(targetId, id, metadata); } public static Task CreateChannelAsync(this IDmtpActorObject client, string targetId, Metadata metadata = default) { - return client.DmtpActor.CreateChannelAsync(targetId,metadata); + return client.DmtpActor.CreateChannelAsync(targetId, metadata); } public static bool TrySubscribeChannel(this IDmtpActorObject client, int id, out IDmtpChannel channel) @@ -403,7 +403,7 @@ namespace TouchSocket.Dmtp /// /// /// - public static void Send(this IDmtpActorObject client, ushort protocol, byte[] buffer,int offset,int length) + public static void Send(this IDmtpActorObject client, ushort protocol, byte[] buffer, int offset, int length) { client.DmtpActor.Send(protocol, buffer, offset, length); } diff --git a/src/TouchSocket.Dmtp/Extensions/DmtpConfigExtension.cs b/src/TouchSocket.Dmtp/Extensions/DmtpConfigExtension.cs index e72e80f56..03b2a481b 100644 --- a/src/TouchSocket.Dmtp/Extensions/DmtpConfigExtension.cs +++ b/src/TouchSocket.Dmtp/Extensions/DmtpConfigExtension.cs @@ -1,6 +1,4 @@ -using System; -using System.Net.Sockets; -using TouchSocket.Core; +using TouchSocket.Core; using TouchSocket.Sockets; namespace TouchSocket.Dmtp @@ -92,7 +90,28 @@ namespace TouchSocket.Dmtp /// /// /// - public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient,new () + + /* 项目“TouchSocket.Dmtp (net7.0)”的未合并的更改 + 在此之前: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient,new () + 在此之后: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient, new() + */ + + /* 项目“TouchSocket.Dmtp (net45)”的未合并的更改 + 在此之前: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient,new () + 在此之后: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient, new() + */ + + /* 项目“TouchSocket.Dmtp (net6.0)”的未合并的更改 + 在此之前: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient,new () + 在此之后: + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config)where TClient : ITcpDmtpClient, new() + */ + public static TClient BuildWithTcpDmtpClient(this TouchSocketConfig config) where TClient : ITcpDmtpClient, new() { return config.BuildClient(); } @@ -113,7 +132,28 @@ namespace TouchSocket.Dmtp /// /// /// - public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService,new () + + /* 项目“TouchSocket.Dmtp (net7.0)”的未合并的更改 + 在此之前: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService,new () + 在此之后: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService, new() + */ + + /* 项目“TouchSocket.Dmtp (net45)”的未合并的更改 + 在此之前: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService,new () + 在此之后: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService, new() + */ + + /* 项目“TouchSocket.Dmtp (net6.0)”的未合并的更改 + 在此之前: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService,new () + 在此之后: + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService, new() + */ + public static TService BuildWithTcpDmtpService(this TouchSocketConfig config) where TService : ITcpDmtpService, new() { return config.BuildService(); } @@ -138,7 +178,7 @@ namespace TouchSocket.Dmtp /// /// /// - public static TClient BuildWithHttpDmtpClient(this TouchSocketConfig config) where TClient : IHttpDmtpClient,new () + public static TClient BuildWithHttpDmtpClient(this TouchSocketConfig config) where TClient : IHttpDmtpClient, new() { return config.BuildClient(); } @@ -159,7 +199,7 @@ namespace TouchSocket.Dmtp /// /// /// - public static TService BuildWithHttpDmtpService(this TouchSocketConfig config) where TService : IHttpDmtpService,new () + public static TService BuildWithHttpDmtpService(this TouchSocketConfig config) where TService : IHttpDmtpService, new() { return config.BuildService(); } diff --git a/src/TouchSocket.Dmtp/Extensions/DmtpFeatureExtension.cs b/src/TouchSocket.Dmtp/Extensions/DmtpFeatureExtension.cs index 856581649..09731bc62 100644 --- a/src/TouchSocket.Dmtp/Extensions/DmtpFeatureExtension.cs +++ b/src/TouchSocket.Dmtp/Extensions/DmtpFeatureExtension.cs @@ -1,16 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp { /// /// DmtpFeatureExtension /// public static class DmtpFeatureExtension { - + } } diff --git a/src/TouchSocket.Dmtp/Extensions/DmtpPluginsManagerExtension.cs b/src/TouchSocket.Dmtp/Extensions/DmtpPluginsManagerExtension.cs index 0918b849d..e3cddb490 100644 --- a/src/TouchSocket.Dmtp/Extensions/DmtpPluginsManagerExtension.cs +++ b/src/TouchSocket.Dmtp/Extensions/DmtpPluginsManagerExtension.cs @@ -25,27 +25,11 @@ namespace TouchSocket.Dmtp /// 默认心跳每3秒进行一次。最大失败3次即判定为断开连接。 /// /// - /// /// /// - public static DmtpHeartbeatPlugin UseDmtpHeartbeat(this IPluginsManager pluginsManager) where TClient : IDmtpActorObject + public static DmtpHeartbeatPlugin UseDmtpHeartbeat(this IPluginsManager pluginsManager) { - var heartbeat = new DmtpHeartbeatPlugin(); - pluginsManager.Add(heartbeat); - return heartbeat; - } - - /// - /// DmtpRpc心跳。客户端、服务器均,但是一般建议仅客户端使用即可。 - /// - /// 默认心跳每3秒进行一次。最大失败3次即判定为断开连接。 - /// - /// - /// - /// - public static DmtpHeartbeatPlugin UseDmtpHeartbeat(this IPluginsManager pluginsManager) - { - var heartbeat = new DmtpHeartbeatPlugin(); + var heartbeat = new DmtpHeartbeatPlugin(); pluginsManager.Add(heartbeat); return heartbeat; } diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/DmtpFileTransferActor.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/DmtpFileTransferActor.cs index 4cd06c82a..a5298b96e 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/DmtpFileTransferActor.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/DmtpFileTransferActor.cs @@ -26,14 +26,14 @@ namespace TouchSocket.Dmtp.FileTransfer #region 委托 /// - /// 当文件传输结束之后。并不意味着完成传输,请通过属性值进行判断。 + /// 当文件传输结束之后。并不意味着完成传输,请通过属性值进行判断。 /// - public Action OnFileTransfered { get; set; } + public Action OnFileTransfered { get; set; } /// /// 在文件传输即将进行时触发。 /// - public Action OnFileTransfering { get; set; } + public Action OnFileTransfering { get; set; } #endregion 委托 @@ -70,7 +70,7 @@ namespace TouchSocket.Dmtp.FileTransfer { var waitFileResource = new WaitFileResource(); waitFileResource.UnpackageRouter(byteBlock); - if (this.DmtpActor.AllowRoute && waitFileResource.Route) + if (waitFileResource.Route && this.DmtpActor.AllowRoute) { if (this.DmtpActor.TryRoute(RouteType.PullFile, waitFileResource)) { @@ -81,13 +81,11 @@ namespace TouchSocket.Dmtp.FileTransfer } else { - waitFileResource.UnpackageBody(byteBlock); waitFileResource.Status = TouchSocketDmtpStatus.ClientNotFind.ToValue(); } } else { - waitFileResource.UnpackageBody(byteBlock); waitFileResource.Status = TouchSocketDmtpStatus.RoutingNotAllowed.ToValue(); } waitFileResource.SwitchId(); @@ -197,7 +195,7 @@ namespace TouchSocket.Dmtp.FileTransfer { var waitFileResource = new WaitFileResource(); waitFileResource.UnpackageRouter(byteBlock); - if (this.DmtpActor.AllowRoute && waitFileResource.Route) + if (waitFileResource.Route && this.DmtpActor.AllowRoute) { if (this.DmtpActor.TryRoute(RouteType.PullFile, waitFileResource)) { @@ -208,16 +206,13 @@ namespace TouchSocket.Dmtp.FileTransfer } else { - waitFileResource.UnpackageBody(byteBlock); waitFileResource.Status = TouchSocketDmtpStatus.ClientNotFind.ToValue(); } } else { - waitFileResource.UnpackageBody(byteBlock); waitFileResource.Status = TouchSocketDmtpStatus.RoutingNotAllowed.ToValue(); } - byteBlock.Reset(); waitFileResource.SwitchId(); waitFileResource.Package(byteBlock); @@ -284,6 +279,8 @@ namespace TouchSocket.Dmtp.FileTransfer else { waitFileSection.UnpackageBody(byteBlock); + //this.RequestPushFileSection(waitFileSection); + //Task.Factory.StartNew(this.RequestPushFileSection, waitFileSection); this.RequestPushFileSection(waitFileSection); } } @@ -382,7 +379,7 @@ namespace TouchSocket.Dmtp.FileTransfer { var waitSmallFilePackage = new WaitSmallFilePackage(); waitSmallFilePackage.UnpackageRouter(byteBlock); - if (this.DmtpActor.AllowRoute && waitSmallFilePackage.Route) + if (waitSmallFilePackage.Route && this.DmtpActor.AllowRoute) { if (this.DmtpActor.TryRoute(RouteType.PullFile, waitSmallFilePackage)) { @@ -393,13 +390,11 @@ namespace TouchSocket.Dmtp.FileTransfer } else { - waitSmallFilePackage.UnpackageBody(byteBlock); waitSmallFilePackage.Status = TouchSocketDmtpStatus.ClientNotFind.ToValue(); } } else { - waitSmallFilePackage.UnpackageBody(byteBlock); waitSmallFilePackage.Status = TouchSocketDmtpStatus.RoutingNotAllowed.ToValue(); } byteBlock.Reset(); @@ -450,7 +445,7 @@ namespace TouchSocket.Dmtp.FileTransfer { var waitSmallFilePackage = new WaitSmallFilePackage(); waitSmallFilePackage.UnpackageRouter(byteBlock); - if (this.DmtpActor.AllowRoute && waitSmallFilePackage.Route) + if (waitSmallFilePackage.Route && this.DmtpActor.AllowRoute) { if (this.DmtpActor.TryRoute(RouteType.PullFile, waitSmallFilePackage)) { @@ -461,15 +456,14 @@ namespace TouchSocket.Dmtp.FileTransfer } else { - waitSmallFilePackage.UnpackageBody(byteBlock); waitSmallFilePackage.Status = TouchSocketDmtpStatus.ClientNotFind.ToValue(); } } else { - waitSmallFilePackage.UnpackageBody(byteBlock); waitSmallFilePackage.Status = TouchSocketDmtpStatus.RoutingNotAllowed.ToValue(); } + byteBlock.Reset(); waitSmallFilePackage.SwitchId(); waitSmallFilePackage.Package(byteBlock); @@ -542,11 +536,17 @@ namespace TouchSocket.Dmtp.FileTransfer private string m_rootPath = string.Empty; + /// + public IDmtpActor DmtpActor { get; } + /// /// 文件资源访问接口。 /// public IFileResourceController FileController { get; set; } + /// + public int MaxSmallFileLength { get; set; } = 1024 * 1024; + /// public string RootPath { @@ -558,9 +558,6 @@ namespace TouchSocket.Dmtp.FileTransfer } } - /// - public IDmtpActor DmtpActor { get; } - #endregion 属性 private bool TryFindDmtpFileTransferActor(string targetId, out DmtpFileTransferActor rpcActor) @@ -583,6 +580,11 @@ namespace TouchSocket.Dmtp.FileTransfer return false; } + private string GetFullPath(string path) + { + return this.FileController.GetFullPath(this.m_rootPath, path); + } + #region Id传输 /// @@ -977,7 +979,7 @@ namespace TouchSocket.Dmtp.FileTransfer { case TouchSocketDmtpStatus.Success: { - return new FileSectionResult(ResultCode.Success, waitFile.Value.Array, fileSection); + return new FileSectionResult(ResultCode.Success, waitFile.Value, fileSection); } case TouchSocketDmtpStatus.ResourceHandleNotFind: { @@ -1091,7 +1093,7 @@ namespace TouchSocket.Dmtp.FileTransfer private Result PrivatePushFileSection(string targetId, FileResourceLocator fileResourceLocator, FileSection fileSection, int timeout = 5000, CancellationToken token = default) { fileSection.Status = FileSectionStatus.Transfering; - var fileSectionResult = fileResourceLocator.ReadFileSection(fileSection); + using var fileSectionResult = fileResourceLocator.ReadFileSection(fileSection); if (!fileSectionResult.IsSuccess()) { fileSection.Status = FileSectionStatus.Fail; @@ -1103,12 +1105,12 @@ namespace TouchSocket.Dmtp.FileTransfer TargetId = targetId, Route = targetId.HasValue(), FileSection = fileSection, - Value = new ArraySegment(fileSectionResult.Value) + Value = fileSectionResult.Value }; var waitData = this.DmtpActor.WaitHandlePool.GetWaitData(waitFileSection); - var byteBlock = new ByteBlock(fileSectionResult.Value.Length + 1024); + var byteBlock = new ByteBlock(fileSectionResult.Value.Count + 1024); try { waitFileSection.Package(byteBlock); @@ -1171,7 +1173,7 @@ namespace TouchSocket.Dmtp.FileTransfer try { var waitFinishedPackage = (WaitFinishedPackage)o; - var transferType = TransferType.SectionPull; + var transferType = TransferType.Pull; string resourcePath = default; string savePath = default; var resultThis = Result.Success; @@ -1182,7 +1184,7 @@ namespace TouchSocket.Dmtp.FileTransfer { if (locator.FileAccess == FileAccess.Read) { - transferType = TransferType.SectionPull; + transferType = TransferType.Pull; if (this.FileController.TryRelaseFileResourceLocator(waitFinishedPackage.ResourceHandle, out _)) { waitFinishedPackage.Status = TouchSocketDmtpStatus.Success.ToValue(); @@ -1197,7 +1199,7 @@ namespace TouchSocket.Dmtp.FileTransfer } else { - transferType = TransferType.SectionPush; + transferType = TransferType.Push; if (this.FileController.TryGetFileResourceLocator(waitFinishedPackage.ResourceHandle, out _)) { resourceInfo = locator.FileResourceInfo; @@ -1251,7 +1253,7 @@ namespace TouchSocket.Dmtp.FileTransfer this.DmtpActor.Send(this.m_finishedFileResourceInfo_Response, byteBlock); } - var args = new FileTransferStatusEventArgs( + var args = new FileTransferedEventArgs( transferType, waitFinishedPackage?.Metadata, resourceInfo?.FileInfo, resultThis) { ResourcePath = resourcePath, @@ -1276,14 +1278,14 @@ namespace TouchSocket.Dmtp.FileTransfer try { - var args = new FileOperationEventArgs(TransferType.SectionPull, waitFileResource.Metadata, default) + var args = new FileTransferingEventArgs(TransferType.Pull, waitFileResource.Metadata, default) { ResourcePath = waitFileResource.Path }; - this.OnFileTransfering?.Invoke(this.DmtpActor, args); + this.OnFileTransfering.Invoke(this.DmtpActor, args); - var fullPath = this.FileController.GetFullPath(this.RootPath, args.ResourcePath); + var fullPath = this.GetFullPath(args.ResourcePath); if (args.IsPermitOperation) { @@ -1366,7 +1368,7 @@ namespace TouchSocket.Dmtp.FileTransfer BytePool.Default.Return(buffer); } } - catch (Exception ex) + catch { } } @@ -1381,15 +1383,15 @@ namespace TouchSocket.Dmtp.FileTransfer var waitFileResource = (WaitFileResource)o; try { - var args = new FileOperationEventArgs(TransferType.SectionPush, + var args = new FileTransferingEventArgs(TransferType.Push, waitFileResource.Metadata, waitFileResource.FileInfo) { SavePath = waitFileResource.Path }; - this.OnFileTransfering?.Invoke(this.DmtpActor, args); + this.OnFileTransfering.Invoke(this.DmtpActor, args); - var savePath = this.FileController.GetFullPath(this.RootPath, args.SavePath); + var savePath = this.GetFullPath(args.SavePath); if (args.IsPermitOperation) { @@ -1434,7 +1436,7 @@ namespace TouchSocket.Dmtp.FileTransfer var result = Result.UnknownFail; for (var i = 0; i < 10; i++) { - result = locator.WriteFileSection(waitFileSection.FileSection, waitFileSection.Value.Array); + result = locator.WriteFileSection(waitFileSection.FileSection, waitFileSection.Value); if (result.IsSuccess()) { break; @@ -1478,12 +1480,6 @@ namespace TouchSocket.Dmtp.FileTransfer #region 小文件 - /// - /// 允许传输的小文件的最大长度。默认1024*1024字节。 - /// 注意,当调整该值时,应该和对端保持一致。 - /// - public int MaxSmallFileLength { get; set; } = 1024 * 1024; - /// public PullSmallFileResult PullSmallFile(string targetId, string path, Metadata metadata = null, int timeout = 5000, CancellationToken token = default) { @@ -1727,15 +1723,14 @@ namespace TouchSocket.Dmtp.FileTransfer var resultThis = Result.Success; try { - var args = new FileOperationEventArgs(TransferType.SmallPull, - waitSmallFilePackage.Metadata, default) + var args = new FileTransferingEventArgs(TransferType.SmallPull, waitSmallFilePackage.Metadata, default) { ResourcePath = waitSmallFilePackage.Path }; - this.OnFileTransfering?.Invoke(this.DmtpActor, args); + this.OnFileTransfering.Invoke(this.DmtpActor, args); - var fullPath = this.FileController.GetFullPath(this.RootPath, args.ResourcePath); + var fullPath = this.GetFullPath(args.ResourcePath); waitSmallFilePackage.Path = fullPath; if (args.IsPermitOperation) { @@ -1790,7 +1785,7 @@ namespace TouchSocket.Dmtp.FileTransfer this.DmtpActor.Send(this.m_pullSmallFile_Response, byteBlock); } - var resultArgs = new FileTransferStatusEventArgs( + var resultArgs = new FileTransferedEventArgs( TransferType.SmallPull, waitSmallFilePackage.Metadata, waitSmallFilePackage.FileInfo, resultThis) { ResourcePath = waitSmallFilePackage.Path @@ -1817,15 +1812,15 @@ namespace TouchSocket.Dmtp.FileTransfer var resultThis = Result.Success; try { - var args = new FileOperationEventArgs(TransferType.SmallPush, + var args = new FileTransferingEventArgs(TransferType.SmallPush, waitSmallFilePackage.Metadata, waitSmallFilePackage.FileInfo) { SavePath = waitSmallFilePackage.Path }; - this.OnFileTransfering?.Invoke(this.DmtpActor, args); + this.OnFileTransfering.Invoke(this.DmtpActor, args); - var fullPath = this.FileController.GetFullPath(this.RootPath, args.SavePath); + var fullPath = this.GetFullPath(args.SavePath); waitSmallFilePackage.Path = fullPath; if (args.IsPermitOperation) { @@ -1853,7 +1848,7 @@ namespace TouchSocket.Dmtp.FileTransfer this.DmtpActor.Send(this.m_pushSmallFile_Response, byteBlock); } - var resultArgs = new FileTransferStatusEventArgs( + var resultArgs = new FileTransferedEventArgs( TransferType.SmallPush, waitSmallFilePackage.Metadata, waitSmallFilePackage.FileInfo, resultThis) { SavePath = waitSmallFilePackage.Path @@ -1886,7 +1881,7 @@ namespace TouchSocket.Dmtp.FileTransfer var resourceInfoResult = this.PullFileResourceInfo(targetId, fileOperator.ResourcePath, fileOperator.Metadata, fileOperator.FileSectionSize, (int)fileOperator.Timeout.TotalMilliseconds, fileOperator.Token); if (resourceInfoResult.NotSuccess()) { - return new Result(resourceInfoResult); + return fileOperator.SetResult(new Result(resourceInfoResult)); } var resourceInfo = resourceInfoResult.FileResourceInfo; if (fileOperator.ResourceInfo == null) @@ -1899,7 +1894,7 @@ namespace TouchSocket.Dmtp.FileTransfer fileOperator.ResourceInfo.ResetResourceHandle(resourceInfo.ResourceHandle); } - var locator = new FileResourceLocator(fileOperator.ResourceInfo, fileOperator.SavePath); + var locator = new FileResourceLocator(fileOperator.ResourceInfo, this.GetFullPath(fileOperator.SavePath)); var sections = new ConcurrentQueue(); foreach (var item in locator.FileResourceInfo.FileSections) { @@ -1959,7 +1954,7 @@ namespace TouchSocket.Dmtp.FileTransfer } } }); - task.Wait(); + task.ConfigureAwait(false).GetAwaiter().GetResult(); if (fileOperator.Token.IsCancellationRequested) { return fileOperator.SetResult(Result.Canceled); @@ -1967,7 +1962,7 @@ namespace TouchSocket.Dmtp.FileTransfer var result1 = locator.TryFinished(); if (this.DmtpActor.IsHandshaked) { - this.FinishedFileResourceInfo(targetId, resourceInfo); + this.FinishedFileResourceInfo(targetId, resourceInfo,fileOperator.Metadata,(int)fileOperator.Timeout.TotalMilliseconds,fileOperator.Token); } return result1.IsSuccess() ? fileOperator.SetResult(Result.Success) : fileOperator.SetResult(failResult); @@ -1983,7 +1978,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return Task.Run(() => { - return PullFile(targetId, fileOperator); + return this.PullFile(targetId, fileOperator); }); } @@ -2003,7 +1998,7 @@ namespace TouchSocket.Dmtp.FileTransfer { if (fileOperator.ResourceInfo == null) { - fileOperator.ResourceInfo = new FileResourceInfo(fileOperator.ResourcePath, fileOperator.FileSectionSize); + fileOperator.ResourceInfo = new FileResourceInfo(this.GetFullPath(fileOperator.ResourcePath), fileOperator.FileSectionSize); fileOperator.SetLength(fileOperator.ResourceInfo.FileInfo.Length); } using var locator = new FileResourceLocator(fileOperator.ResourceInfo); @@ -2062,8 +2057,8 @@ namespace TouchSocket.Dmtp.FileTransfer } } }); - task.Wait(); - var res = this.FinishedFileResourceInfo(targetId, fileOperator.ResourceInfo); + task.ConfigureAwait(false).GetAwaiter().GetResult(); + var res = this.FinishedFileResourceInfo(targetId, fileOperator.ResourceInfo, fileOperator.Metadata, (int)fileOperator.Timeout.TotalMilliseconds, fileOperator.Token); return fileOperator.Token.IsCancellationRequested ? fileOperator.SetResult(Result.Canceled) : fileOperator.SetResult(res.ToResult()); } catch (Exception ex) @@ -2077,7 +2072,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return Task.Run(() => { - return PushFile(targetId, fileOperator); + return this.PushFile(targetId, fileOperator); }); } @@ -2104,6 +2099,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return new Result(resourceInfoResult); } + var resourceInfo = resourceInfoResult.FileResourceInfo; if (fileOperator.ResourceInfo == null) { @@ -2115,7 +2111,7 @@ namespace TouchSocket.Dmtp.FileTransfer fileOperator.ResourceInfo.ResetResourceHandle(resourceInfo.ResourceHandle); } - var locator = new FileResourceLocator(fileOperator.ResourceInfo, fileOperator.SavePath); + var locator = new FileResourceLocator(fileOperator.ResourceInfo, this.GetFullPath(fileOperator.SavePath)); var sections = new ConcurrentQueue(); foreach (var item in locator.FileResourceInfo.FileSections) { @@ -2176,7 +2172,7 @@ namespace TouchSocket.Dmtp.FileTransfer } } }); - task.Wait(); + task.ConfigureAwait(false).GetAwaiter().GetResult(); if (fileOperator.Token.IsCancellationRequested) { return fileOperator.SetResult(Result.Canceled); @@ -2184,7 +2180,7 @@ namespace TouchSocket.Dmtp.FileTransfer var result1 = locator.TryFinished(); if (this.DmtpActor.IsHandshaked) { - this.FinishedFileResourceInfo(resourceInfo); + this.FinishedFileResourceInfo(resourceInfo,fileOperator.Metadata, (int)fileOperator.Timeout.TotalMilliseconds,fileOperator.Token); } return result1.IsSuccess() ? fileOperator.SetResult(Result.Success) : fileOperator.SetResult(failResult); @@ -2200,7 +2196,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return Task.Run(() => { - return PullFile(fileOperator); + return this.PullFile(fileOperator); }); } @@ -2220,7 +2216,7 @@ namespace TouchSocket.Dmtp.FileTransfer { if (fileOperator.ResourceInfo == null) { - fileOperator.ResourceInfo = new FileResourceInfo(fileOperator.ResourcePath, fileOperator.FileSectionSize); + fileOperator.ResourceInfo = new FileResourceInfo(this.GetFullPath(fileOperator.ResourcePath), fileOperator.FileSectionSize); fileOperator.SetLength(fileOperator.ResourceInfo.FileInfo.Length); } using var locator = new FileResourceLocator(fileOperator.ResourceInfo); @@ -2279,9 +2275,9 @@ namespace TouchSocket.Dmtp.FileTransfer } } }); - task.Wait(); + task.ConfigureAwait(false).GetAwaiter().GetResult(); - var res = this.FinishedFileResourceInfo(fileOperator.ResourceInfo); + var res = this.FinishedFileResourceInfo(fileOperator.ResourceInfo,fileOperator.Metadata,(int)fileOperator.Timeout.TotalMilliseconds,fileOperator.Token); return fileOperator.Token.IsCancellationRequested ? fileOperator.SetResult(Result.Canceled) : fileOperator.SetResult(res.ToResult()); } catch (Exception ex) @@ -2295,7 +2291,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return Task.Run(() => { - return PushFile(fileOperator); + return this.PushFile(fileOperator); }); } diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/IDmtpFileTransferActor.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/IDmtpFileTransferActor.cs index 353e6bffe..ba2ef326e 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/IDmtpFileTransferActor.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Actor/IDmtpFileTransferActor.cs @@ -22,6 +22,17 @@ namespace TouchSocket.Dmtp.FileTransfer /// public interface IDmtpFileTransferActor : IActor { + /// + /// 文件传输的根路径 + /// + string RootPath { get; set; } + + /// + /// 允许传输的小文件的最大长度。默认1024*1024字节。 + /// 注意,当调整该值时,应该和对端保持一致。 + /// + int MaxSmallFileLength { get; set; } + #region Id小文件 /// @@ -103,7 +114,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// 超时设置 /// 可取消令箭 /// - Result PushSmallFile( string savePath, FileInfo fileInfo, Metadata metadata = null, int timeout = 5000, CancellationToken token = default); + Result PushSmallFile(string savePath, FileInfo fileInfo, Metadata metadata = null, int timeout = 5000, CancellationToken token = default); /// /// 推送小文件。默认设置1024*1024字节大小。 @@ -114,7 +125,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// 超时设置 /// 可取消令箭 /// - Task PushSmallFileAsync( string savePath, FileInfo fileInfo, Metadata metadata = null, int timeout = 5000, CancellationToken token = default); + Task PushSmallFileAsync(string savePath, FileInfo fileInfo, Metadata metadata = null, int timeout = 5000, CancellationToken token = default); #endregion 小文件 diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceInfo.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceInfo.cs index c9c67daa5..b567614ae 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceInfo.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceInfo.cs @@ -88,7 +88,7 @@ namespace TouchSocket.Dmtp.FileTransfer } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { byteBlock.Write(this.ResourceHandle); byteBlock.WritePackage(this.FileInfo); @@ -113,7 +113,7 @@ namespace TouchSocket.Dmtp.FileTransfer } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { this.ResourceHandle = byteBlock.ReadInt32(); this.FileInfo = byteBlock.ReadPackage(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceLocator.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceLocator.cs index 15556915d..95eb6d33e 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceLocator.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileResourceLocator.cs @@ -156,11 +156,16 @@ namespace TouchSocket.Dmtp.FileTransfer { return new FileSectionResult(ResultCode.Error, "数据块不一致。", default, fileSection); } - var buffer = new byte[fileSection.Length]; - var r = this.FileStorage.Read(oldFileSection.Offset, buffer, 0, buffer.Length); - return r != fileSection.Length - ? new FileSectionResult(ResultCode.Error, "读取长度不一致。", default, fileSection) - : new FileSectionResult(ResultCode.Success, buffer, fileSection); + var buffer = BytePool.Default.Rent(fileSection.Length); + var r = this.FileStorage.Read(oldFileSection.Offset, buffer, 0, fileSection.Length); + if (r != fileSection.Length) + { + return new FileSectionResult(ResultCode.Error, "读取长度不一致。", default, fileSection); + } + else + { + return new FileSectionResult(ResultCode.Success, new ArraySegment(buffer, 0, r), fileSection); + } } catch (Exception ex) { @@ -236,7 +241,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// /// - public Result WriteFileSection(FileSection fileSection, byte[] value) + public Result WriteFileSection(FileSection fileSection, ArraySegment value) { try { @@ -254,7 +259,7 @@ namespace TouchSocket.Dmtp.FileTransfer var srcFileSection = this.FileResourceInfo.FileSections[fileSection.Index]; - if (value.Length != fileSection.Length) + if (value.Count != fileSection.Length) { fileSection.Status = FileSectionStatus.Fail; return new Result(ResultCode.Error, "实际数据长度与期望长度不一致。"); @@ -264,7 +269,7 @@ namespace TouchSocket.Dmtp.FileTransfer { return new Result(ResultCode.Error, "数据块不一致。"); } - this.FileStorage.Write(srcFileSection.Offset, value, 0, value.Length); + this.FileStorage.Write(srcFileSection.Offset, value.Array, value.Offset, value.Count); fileSection.Status = FileSectionStatus.Finished; srcFileSection.Status = FileSectionStatus.Finished; return Result.Success; @@ -283,11 +288,21 @@ namespace TouchSocket.Dmtp.FileTransfer public Result WriteFileSection(FileSectionResult fileSectionResult) { this.LastActiveTime = DateTime.Now; - return this.FileAccess != FileAccess.Write - ? new Result(ResultCode.Error, "该定位器是只读的。") - : !fileSectionResult.IsSuccess() - ? new Result(fileSectionResult) - : this.WriteFileSection(fileSectionResult.FileSection, fileSectionResult.Value); + if (this.FileAccess != FileAccess.Write) + { + return new Result(ResultCode.Error, "该定位器是只读的。"); + } + else + { + if (!fileSectionResult.IsSuccess()) + { + return new Result(fileSectionResult); + } + else + { + return this.WriteFileSection(fileSectionResult.FileSection, fileSectionResult.Value); + } + } } /// diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSection.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSection.cs index 427c75337..2b8a093e9 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSection.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSection.cs @@ -45,7 +45,7 @@ namespace TouchSocket.Dmtp.FileTransfer public int Length { get; internal set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { byteBlock.Write((byte)this.Status); byteBlock.Write(this.ResourceHandle); @@ -55,7 +55,7 @@ namespace TouchSocket.Dmtp.FileTransfer } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { this.Status = (FileSectionStatus)byteBlock.ReadByte(); this.ResourceHandle = byteBlock.ReadInt32(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionResult.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionResult.cs index 86145ce3e..d3efe74d1 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionResult.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionResult.cs @@ -10,6 +10,7 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using System; using TouchSocket.Core; namespace TouchSocket.Dmtp.FileTransfer @@ -17,7 +18,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// FileSectionResult /// - public class FileSectionResult : ResultBase + public class FileSectionResult : ResultBase, IDisposable { /// /// FileSectionResult @@ -25,7 +26,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// /// - public FileSectionResult(ResultCode resultCode, byte[] value, FileSection fileSection) : base(resultCode) + public FileSectionResult(ResultCode resultCode, ArraySegment value, FileSection fileSection) : base(resultCode) { this.Value = value; this.FileSection = fileSection; @@ -38,7 +39,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// /// - public FileSectionResult(ResultCode resultCode, string message, byte[] value, FileSection fileSection) : base(resultCode, message) + public FileSectionResult(ResultCode resultCode, string message, ArraySegment value, FileSection fileSection) : base(resultCode, message) { this.Value = value; this.FileSection = fileSection; @@ -52,6 +53,18 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// 实际数据 /// - public byte[] Value { get; private set; } + public ArraySegment Value { get; private set; } + + /// + /// Dispose + /// + /// + public void Dispose() + { + if (this.Value.Count > 0) + { + BytePool.Default.Return(this.Value.Array); + } + } } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionStatus.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionStatus.cs index 03a60568d..b7f5c51c8 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionStatus.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/FileSectionStatus.cs @@ -10,7 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using TouchSocket.Core; namespace TouchSocket.Dmtp.FileTransfer { diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileInfo.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileInfo.cs index 5341c3d21..d13d0241d 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileInfo.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileInfo.cs @@ -54,7 +54,7 @@ namespace TouchSocket.Dmtp.FileTransfer public string MD5 { get; set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { base.Package(byteBlock); byteBlock.Write(this.MD5); @@ -62,7 +62,7 @@ namespace TouchSocket.Dmtp.FileTransfer } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { base.Unpackage(byteBlock); this.MD5 = byteBlock.ReadString(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileSystemInfo.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileSystemInfo.cs index ac310ad42..a9c2340db 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileSystemInfo.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/RemoteFileSystemInfo.cs @@ -52,7 +52,7 @@ namespace TouchSocket.Dmtp.FileTransfer public string Name { get; set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { byteBlock.Write(this.LastWriteTime); byteBlock.Write(this.LastAccessTime); @@ -63,7 +63,7 @@ namespace TouchSocket.Dmtp.FileTransfer } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { this.LastWriteTime = byteBlock.ReadDateTime(); this.LastAccessTime = byteBlock.ReadDateTime(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/TouchRpcFileInfo.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/TouchRpcFileInfo.cs index cb4a29528..a2bbfd94b 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/TouchRpcFileInfo.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/TouchRpcFileInfo.cs @@ -26,14 +26,14 @@ namespace TouchSocket.Dmtp.FileTransfer public long Position { get; set; } /// - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { base.Package(byteBlock); byteBlock.Write(this.Position); } /// - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { base.Unpackage(byteBlock); this.Position = byteBlock.ReadInt64(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileInfoPackage.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileInfoPackage.cs index 7cb7471d1..c8ba5ed1d 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileInfoPackage.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileInfoPackage.cs @@ -29,11 +29,6 @@ namespace TouchSocket.Dmtp.FileTransfer /// public TouchRpcFileInfo FileInfo { get; set; } - /// - /// 传输标识 - /// - public TransferFlags Flags { get; set; } - /// /// 存放路径, /// 可输入绝对路径,也可以输入相对路径。 @@ -52,23 +47,21 @@ namespace TouchSocket.Dmtp.FileTransfer /// public int EventHashCode { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.WritePackage(this.Metadata); byteBlock.WritePackage(this.FileInfo); - byteBlock.Write((byte)this.Flags); byteBlock.Write(this.SavePath); byteBlock.Write(this.ResourcePath); byteBlock.Write(this.EventHashCode); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.Metadata = byteBlock.ReadPackage(); this.FileInfo = byteBlock.ReadPackage(); - this.Flags = (TransferFlags)byteBlock.ReadByte(); this.SavePath = byteBlock.ReadString(); this.ResourcePath = byteBlock.ReadString(); this.EventHashCode = byteBlock.ReadInt32(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileResource.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileResource.cs index 1e20e7d7c..447f15355 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileResource.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileResource.cs @@ -16,13 +16,15 @@ namespace TouchSocket.Dmtp.FileTransfer { internal class WaitFileResource : WaitRouterPackage { + protected override bool IncludedRouter => true; + public RemoteFileInfo FileInfo { get; set; } public Metadata Metadata { get; set; } public string Path { get; set; } public int ResourceHandle { get; set; } public int FileSectionSize { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write(this.Path); @@ -32,7 +34,7 @@ namespace TouchSocket.Dmtp.FileTransfer byteBlock.WritePackage(this.Metadata); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.Path = byteBlock.ReadString(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileSection.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileSection.cs index b1a49a643..ea2168323 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileSection.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFileSection.cs @@ -20,7 +20,7 @@ namespace TouchSocket.Dmtp.FileTransfer public FileSection FileSection { get; set; } public ArraySegment Value { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.WritePackage(this.FileSection); @@ -35,7 +35,7 @@ namespace TouchSocket.Dmtp.FileTransfer } } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.FileSection = byteBlock.ReadPackage(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFinishedPackage.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFinishedPackage.cs index cec91782a..5a5fb860c 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFinishedPackage.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitFinishedPackage.cs @@ -25,7 +25,7 @@ namespace TouchSocket.Dmtp.FileTransfer public int ResourceHandle { get; set; } public int[] UnFinishedIndexs { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write(this.ResourceHandle); @@ -37,7 +37,7 @@ namespace TouchSocket.Dmtp.FileTransfer } } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.ResourceHandle = byteBlock.ReadInt32(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitSmallFilePackage.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitSmallFilePackage.cs index 51b467d53..a04e78143 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitSmallFilePackage.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Common/WaitSmallFilePackage.cs @@ -16,13 +16,14 @@ namespace TouchSocket.Dmtp.FileTransfer { internal class WaitSmallFilePackage : WaitRouterPackage { + protected override bool IncludedRouter => true; public byte[] Data { get; set; } public RemoteFileInfo FileInfo { get; set; } public int Len { get; set; } public Metadata Metadata { get; set; } public string Path { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write(this.Path); @@ -31,7 +32,7 @@ namespace TouchSocket.Dmtp.FileTransfer byteBlock.WriteBytesPackage(this.Data, 0, this.Len); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.Path = byteBlock.ReadString(); diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferActorExtension.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferActorExtension.cs index 4fa9046bc..1b1a525e6 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferActorExtension.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferActorExtension.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Resources; diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferFeature.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferFeature.cs index 60b19f479..1cf7a770c 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferFeature.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/DmtpFileTransferFeature.cs @@ -20,12 +20,19 @@ namespace TouchSocket.Dmtp.FileTransfer { this.m_fileResourceController = container.TryResolve() ?? new FileResourceController(); this.m_pluginsManager = pluginsManager; + this.MaxSmallFileLength = 1024 * 1024; this.SetProtocolFlags(30); } + /// + public int MaxSmallFileLength { get; set; } + /// public ushort ReserveProtocolSize => 20; + /// + public string RootPath { get; set; } + /// public ushort StartProtocol { get; set; } @@ -35,9 +42,10 @@ namespace TouchSocket.Dmtp.FileTransfer { FileController = m_fileResourceController, OnFileTransfering = OnFileTransfering, - OnFileTransfered = OnFileTransfered + OnFileTransfered = OnFileTransfered, + RootPath = this.RootPath, + MaxSmallFileLength = this.MaxSmallFileLength }; - smtpFileTransferActor.SetProtocolFlags(this.StartProtocol); client.DmtpActor.SetDmtpFileTransferActor(smtpFileTransferActor); @@ -58,6 +66,13 @@ namespace TouchSocket.Dmtp.FileTransfer return e.InvokeNext(); } + /// + public DmtpFileTransferFeature SetMaxSmallFileLength(int maxSmallFileLength) + { + this.MaxSmallFileLength = maxSmallFileLength; + return this; + } + /// /// 设置的起始协议。 /// @@ -72,12 +87,19 @@ namespace TouchSocket.Dmtp.FileTransfer return this; } - private void OnFileTransfered(IDmtpActor actor, FileTransferStatusEventArgs e) + /// + public DmtpFileTransferFeature SetRootPath(string rootPath) + { + this.RootPath = rootPath; + return this; + } + + private void OnFileTransfered(IDmtpActor actor, FileTransferedEventArgs e) { this.m_pluginsManager.Raise(nameof(IDmtpFileTransferedPlugin.OnDmtpFileTransfered), actor.Client, e); } - private void OnFileTransfering(IDmtpActor actor, FileOperationEventArgs e) + private void OnFileTransfering(IDmtpActor actor, FileTransferingEventArgs e) { this.m_pluginsManager.Raise(nameof(IDmtpFileTransferingPlugin.OnDmtpFileTransfering), actor.Client, e); } diff --git a/src/TouchSocket.JsonRpc/Enum/JRPT.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Enum/TransferType.cs similarity index 75% rename from src/TouchSocket.JsonRpc/Enum/JRPT.cs rename to src/TouchSocket.Dmtp/Features/FileTransfer/Enum/TransferType.cs index ba5728bbe..65cad8a30 100644 --- a/src/TouchSocket.JsonRpc/Enum/JRPT.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Enum/TransferType.cs @@ -10,26 +10,37 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -namespace TouchSocket.JsonRpc + +using System; + +namespace TouchSocket.Dmtp.FileTransfer { /// - /// JsonRpc协议类型 + /// 传输类型 /// - public enum JRPT : byte + [Flags] + public enum TransferType { /// - /// 普通TCP协议 + /// 推送 /// - Tcp, + Push, /// - /// Http协议 + /// 拉取 /// - Http, + Pull, /// - /// Websocket协议 + /// 小文件推送 /// - Websocket + SmallPush, + + /// + /// 小文件拉取 + /// + SmallPull } + + } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileOperationEventArgs.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileOperationEventArgs.cs deleted file mode 100644 index 4de0e9876..000000000 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileOperationEventArgs.cs +++ /dev/null @@ -1,119 +0,0 @@ -//------------------------------------------------------------------------------ -// 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 -// 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 -// CSDN博客:https://blog.csdn.net/qq_40374647 -// 哔哩哔哩视频:https://space.bilibili.com/94253567 -// Gitee源代码仓库:https://gitee.com/RRQM_Home -// Github源代码仓库:https://github.com/RRQM -// API首页:http://rrqm_home.gitee.io/touchsocket/ -// 交流QQ群:234762506 -// 感谢您的下载和使用 -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ -using TouchSocket.Core; - -namespace TouchSocket.Dmtp.FileTransfer -{ - /// - /// 操作文件事件类 - /// - public class FileOperationEventArgs : MsgPermitEventArgs - { - private string m_savePath; - private string m_resourcePath; - private readonly Metadata m_metadata; - - /// - /// FileOperationEventArgs - /// - /// - /// - /// - public FileOperationEventArgs(TransferType transferType, FileOperator fileOperator, RemoteFileInfo fileInfo) - { - this.FileOperator = fileOperator; - this.TransferType = transferType; - this.FileInfo = fileInfo; - } - - /// - /// FileOperationEventArgs - /// - /// - /// - /// - public FileOperationEventArgs(TransferType transferType, Metadata metadata, RemoteFileInfo fileInfo) - { - this.FileOperator = default; - this.TransferType = transferType; - this.FileInfo = fileInfo; - this.m_metadata = metadata; - } - - /// - /// 存放路径, - /// 可输入绝对路径,也可以输入相对路径。 - /// 但是必须包含文件名及扩展名。 - /// - public string SavePath - { - get => this.FileOperator == null ? this.m_savePath : this.FileOperator.SavePath; - set - { - if (this.FileOperator == null) - { - this.m_savePath = value; - } - else - { - this.FileOperator.SavePath = value; - } - } - } - - /// - /// 请求文件路径, - /// 可输入绝对路径,也可以输入相对路径。 - /// - public string ResourcePath - { - get => this.FileOperator == null ? this.m_resourcePath : this.FileOperator.ResourcePath; - set - { - if (this.FileOperator == null) - { - this.m_resourcePath = value; - } - else - { - this.FileOperator.ResourcePath = value; - } - } - } - - /// - /// 元数据 - /// - public Metadata Metadata => this.FileOperator == null ? this.m_metadata : this.FileOperator.Metadata; - - /// - /// 文件操作器 - /// - public FileOperator FileOperator { get; private set; } - - /// - /// 文件信息 - /// - public RemoteFileInfo FileInfo { get; private set; } - - ///// - ///// 传输标识 - ///// - //public TransferFlags Flags { get => this.FileOperator == null ? TransferFlags.None : this.FileOperator.Flags; } - - /// - /// 传输类型 - /// - public TransferType TransferType { get; private set; } - } -} \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferStatusEventArgs.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferStatusEventArgs.cs deleted file mode 100644 index 0d56d1401..000000000 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferStatusEventArgs.cs +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------ -// 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 -// 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 -// CSDN博客:https://blog.csdn.net/qq_40374647 -// 哔哩哔哩视频:https://space.bilibili.com/94253567 -// Gitee源代码仓库:https://gitee.com/RRQM_Home -// Github源代码仓库:https://github.com/RRQM -// API首页:http://rrqm_home.gitee.io/touchsocket/ -// 交流QQ群:234762506 -// 感谢您的下载和使用 -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ -using TouchSocket.Core; - -namespace TouchSocket.Dmtp.FileTransfer -{ - /// - /// 文件传输状态 - /// - public class FileTransferStatusEventArgs : FileOperationEventArgs - { - /// - /// FileTransferStatusEventArgs - /// - /// - /// - /// - /// - public FileTransferStatusEventArgs(TransferType transferType, Metadata metadata, RemoteFileInfo fileInfo, Result result) - : base(transferType, metadata, fileInfo) - { - this.Result = result; - } - - /// - /// FileTransferStatusEventArgs - /// - /// - /// - /// - /// - public FileTransferStatusEventArgs(TransferType transferType, Result result, RemoteFileInfo fileInfo, FileOperator fileOperator) - : base(transferType, fileOperator, fileInfo) - { - this.Result = result; - } - - /// - /// FileTransferStatusEventArgs - /// - /// - /// - public FileTransferStatusEventArgs(Result result, FileOperationEventArgs args) - : base(args.TransferType, args.FileOperator, args.FileInfo) - { - this.Result = result; - } - - /// - /// 结果 - /// - public Result Result { get; private set; } - } -} \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Enum/TransferFlags.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferedEventArgs.cs similarity index 55% rename from src/TouchSocket.Dmtp/Enum/TransferFlags.cs rename to src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferedEventArgs.cs index dc0eb355b..094919661 100644 --- a/src/TouchSocket.Dmtp/Enum/TransferFlags.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferedEventArgs.cs @@ -10,36 +10,31 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System; +using TouchSocket.Core; -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp.FileTransfer { /// - /// 传输标识 + /// FileTransferedEventArgs /// - [Flags] - public enum TransferFlags : byte + public class FileTransferedEventArgs : FileTransferingEventArgs { /// - /// 无任何标识 + /// FileTransferedEventArgs /// - None = 0, + /// + /// + /// + /// + public FileTransferedEventArgs(TransferType transferType, Metadata metadata, RemoteFileInfo fileInfo, Result result) + : base(transferType, metadata, fileInfo) + { + this.Result = result; + } /// - /// 断点续传。 - /// 使用该标识时,会使用文件长度验证续传的有效性。如果需要,也可以附加验证。 + /// 结果 /// - BreakpointResume = 1, - - /// - /// MD5验证。该标识在文件传输完成时,也会再次验证文件长度。 - /// - MD5Verify = 2, - - /// - /// 当传输失败时,删除所有缓存文件。 - /// 注意:当启用断点续传时,该标识无效 - /// - DeleteWhenFail = 4 + public Result Result { get; private set; } } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Enum/TransferType.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferingEventArgs.cs similarity index 52% rename from src/TouchSocket.Dmtp/Enum/TransferType.cs rename to src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferingEventArgs.cs index 855f98d30..59ad7de26 100644 --- a/src/TouchSocket.Dmtp/Enum/TransferType.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/EventArgs/FileTransferingEventArgs.cs @@ -10,61 +10,54 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using TouchSocket.Core; -using System; - -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp.FileTransfer { /// - /// 传输类型 + /// FileTransferingEventArgs /// - [Flags] - public enum TransferType + public class FileTransferingEventArgs : MsgPermitEventArgs { /// - /// 推送 - /// - Push = 0, - - /// - /// 拉取 - /// - Pull = 1, - - /// - /// 分块推送 - /// - SectionPush = 2, - - /// - /// 分块拉取 - /// - SectionPull = 4, - - /// - /// 小文件推送 - /// - SmallPush = 8, - - /// - /// 小文件拉取 - /// - SmallPull = 16 - } - - /// - /// TransferTypeExtension - /// - public static class TransferTypeExtension - { - /// - /// 表示当前传输类型是否属于其中的一种。 + /// FileTransferingEventArgs /// /// - /// - public static bool IsPull(this TransferType transferType) + /// + /// + public FileTransferingEventArgs(TransferType transferType, Metadata metadata, RemoteFileInfo fileInfo) { - return transferType == TransferType.Pull || transferType == TransferType.SmallPull || transferType == TransferType.SectionPull; + this.TransferType = transferType; + this.FileInfo = fileInfo; + this.Metadata = metadata; } + + /// + /// 存放路径, + /// 可输入绝对路径,也可以输入相对路径。 + /// 但是必须包含文件名及扩展名。 + /// + public string SavePath { get; set; } + + /// + /// 请求文件路径, + /// 可输入绝对路径,也可以输入相对路径。 + /// + public string ResourcePath { get; set; } + + /// + /// 元数据 + /// + public Metadata Metadata { get; private set; } + + /// + /// 文件信息 + /// + public RemoteFileInfo FileInfo { get; private set; } + + /// + /// 传输类型 + /// + public TransferType TransferType { get; private set; } } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Extensions/TransferTypeExtension.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Extensions/TransferTypeExtension.cs new file mode 100644 index 000000000..7cdb8d70a --- /dev/null +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Extensions/TransferTypeExtension.cs @@ -0,0 +1,18 @@ +namespace TouchSocket.Dmtp.FileTransfer +{ + /// + /// TransferTypeExtension + /// + public static class TransferTypeExtension + { + /// + /// 表示当前传输类型是否属于其中的一种。 + /// + /// + /// + public static bool IsPull(this TransferType transferType) + { + return transferType == TransferType.Pull || transferType == TransferType.SmallPull; + } + } +} diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferedPlugin.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferedPlugin.cs index 079ffba30..3d5ec66fe 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferedPlugin.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferedPlugin.cs @@ -6,23 +6,23 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// IDmtpFileTransferedPlugin /// - public interface IDmtpFileTransferedPlugin : IPlugin where TClient: IDmtpActorObject + public interface IDmtpFileTransferedPlugin : IPlugin where TClient : IDmtpActorObject { /// - /// 当文件传输结束之后。并不意味着完成传输,请通过属性值进行判断。 + /// 当文件传输结束之后。并不意味着完成传输,请通过属性值进行判断。 /// /// /// /// - Task OnDmtpFileTransfered(TClient client, FileTransferStatusEventArgs e); + Task OnDmtpFileTransfered(TClient client, FileTransferedEventArgs e); } /// /// IDmtpFileTransferedPlugin /// - public interface IDmtpFileTransferedPlugin: IDmtpFileTransferedPlugin - { - + public interface IDmtpFileTransferedPlugin : IDmtpFileTransferedPlugin + { + } } diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferingPlugin.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferingPlugin.cs index 9b4f72d2e..6a2c031b7 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferingPlugin.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Plugins/IDmtpFileTransferingPlugin.cs @@ -6,7 +6,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// IDmtpFileTransferPlugin /// - public interface IDmtpFileTransferingPlugin : IPlugin where TClient:IDmtpActorObject + public interface IDmtpFileTransferingPlugin : IPlugin where TClient : IDmtpActorObject { /// /// 在文件传输即将进行时触发。 @@ -14,14 +14,14 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// /// - Task OnDmtpFileTransfering(TClient client, FileOperationEventArgs e); + Task OnDmtpFileTransfering(TClient client, FileTransferingEventArgs e); } /// /// IDmtpFileTransferingPlugin /// - public interface IDmtpFileTransferingPlugin: IDmtpFileTransferingPlugin + public interface IDmtpFileTransferingPlugin : IDmtpFileTransferingPlugin { } diff --git a/src/TouchSocket.Dmtp/Features/FileTransfer/Services/IFileResourceController.cs b/src/TouchSocket.Dmtp/Features/FileTransfer/Services/IFileResourceController.cs index 88bacf43a..e078ce418 100644 --- a/src/TouchSocket.Dmtp/Features/FileTransfer/Services/IFileResourceController.cs +++ b/src/TouchSocket.Dmtp/Features/FileTransfer/Services/IFileResourceController.cs @@ -19,7 +19,7 @@ namespace TouchSocket.Dmtp.FileTransfer /// /// 文件资源控制器。 /// - public interface IFileResourceController:IDisposable + public interface IFileResourceController : IDisposable { /// /// 文件资源字典,在该字典中存着正在传输,或者传输异常的资源。 diff --git a/src/TouchSocket.Dmtp/Features/Redis/RedisFeature.cs b/src/TouchSocket.Dmtp/Features/Redis/RedisFeature.cs index c6b9eaf74..419febebe 100644 --- a/src/TouchSocket.Dmtp/Features/Redis/RedisFeature.cs +++ b/src/TouchSocket.Dmtp/Features/Redis/RedisFeature.cs @@ -25,7 +25,7 @@ namespace TouchSocket.Dmtp.Redis /// public RedisFeature() { - SetProtocolFlags(25); + this.SetProtocolFlags(25); } /// diff --git a/src/TouchSocket.Dmtp/Features/Redis/RedisRequestWaitPackage.cs b/src/TouchSocket.Dmtp/Features/Redis/RedisRequestWaitPackage.cs index 1c9176d7f..cdc1ad7d1 100644 --- a/src/TouchSocket.Dmtp/Features/Redis/RedisRequestWaitPackage.cs +++ b/src/TouchSocket.Dmtp/Features/Redis/RedisRequestWaitPackage.cs @@ -21,7 +21,7 @@ namespace TouchSocket.Dmtp.Redis public TimeSpan? timeSpan; public RedisPackageType packageType; - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { base.Package(byteBlock); byteBlock.Write(this.key); @@ -37,7 +37,7 @@ namespace TouchSocket.Dmtp.Redis } } - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { base.Unpackage(byteBlock); this.key = byteBlock.ReadString(); diff --git a/src/TouchSocket.Dmtp/Features/Redis/RedisResponseWaitPackage.cs b/src/TouchSocket.Dmtp/Features/Redis/RedisResponseWaitPackage.cs index bc08c44c6..95759755e 100644 --- a/src/TouchSocket.Dmtp/Features/Redis/RedisResponseWaitPackage.cs +++ b/src/TouchSocket.Dmtp/Features/Redis/RedisResponseWaitPackage.cs @@ -18,13 +18,13 @@ namespace TouchSocket.Dmtp.Redis { public byte[] value; - public override void Package(ByteBlock byteBlock) + public override void Package(in ByteBlock byteBlock) { base.Package(byteBlock); byteBlock.WriteBytesPackage(this.value); } - public override void Unpackage(ByteBlock byteBlock) + public override void Unpackage(in ByteBlock byteBlock) { base.Unpackage(byteBlock); this.value = byteBlock.ReadBytesPackage(); diff --git a/src/TouchSocket.Dmtp/Features/Rpc/Actor/DmtpRpcActor.cs b/src/TouchSocket.Dmtp/Features/Rpc/Actor/DmtpRpcActor.cs index f6f46af3f..39c21432a 100644 --- a/src/TouchSocket.Dmtp/Features/Rpc/Actor/DmtpRpcActor.cs +++ b/src/TouchSocket.Dmtp/Features/Rpc/Actor/DmtpRpcActor.cs @@ -13,12 +13,10 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Resources; using TouchSocket.Rpc; -using TouchSocket.Sockets; namespace TouchSocket.Dmtp.Rpc { @@ -27,7 +25,6 @@ namespace TouchSocket.Dmtp.Rpc /// public class DmtpRpcActor : ConcurrentDictionary, IDmtpRpcActor { - /// /// 创建一个DmtpRpcActor /// @@ -37,6 +34,9 @@ namespace TouchSocket.Dmtp.Rpc this.DmtpActor = smtpActor; } + /// + public IDmtpActor DmtpActor { get; } + /// /// 获取调用的函数 /// @@ -48,14 +48,12 @@ namespace TouchSocket.Dmtp.Rpc /// public SerializationSelector SerializationSelector { get; set; } - /// - public IDmtpActor DmtpActor { get; } #region 字段 private ushort m_cancelInvoke; private ushort m_invoke_Request; private ushort m_invoke_Response; - + #endregion 字段 /// @@ -66,14 +64,14 @@ namespace TouchSocket.Dmtp.Rpc public bool InputReceivedData(DmtpMessage message) { var byteBlock = message.BodyByteBlock; - + if (message.ProtocolFlags == this.m_invoke_Request) { try { var rpcPackage = new DmtpRpcPackage(); rpcPackage.UnpackageRouter(byteBlock); - if (this.DmtpActor.AllowRoute && rpcPackage.Route) + if (rpcPackage.Route && this.DmtpActor.AllowRoute) { if (this.DmtpActor.TryRoute(RouteType.Rpc, rpcPackage)) { @@ -84,13 +82,11 @@ namespace TouchSocket.Dmtp.Rpc } else { - rpcPackage.UnpackageBody(byteBlock); rpcPackage.Status = TouchSocketDmtpStatus.ClientNotFind.ToValue(); } } else { - rpcPackage.UnpackageBody(byteBlock); rpcPackage.Status = TouchSocketDmtpStatus.RoutingNotAllowed.ToValue(); } @@ -104,7 +100,6 @@ namespace TouchSocket.Dmtp.Rpc { rpcPackage.UnpackageBody(byteBlock); Task.Factory.StartNew(this.InvokeThis, rpcPackage); - //this.InvokeThis(rpcPackage); } } catch (Exception ex) @@ -280,7 +275,7 @@ namespace TouchSocket.Dmtp.Rpc { transientRpcServer.CallContext = callContext; } - invokeResult =RpcStore.Execute(rpcServer, ps, callContext); + invokeResult = RpcStore.Execute(rpcServer, ps, callContext); } if (rpcPackage.Feedback == FeedbackType.OnlySend) @@ -419,7 +414,7 @@ namespace TouchSocket.Dmtp.Rpc case FeedbackType.OnlySend: { this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); - return default; + return returnType.GetDefault(); } case FeedbackType.WaitSend: { @@ -435,7 +430,7 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } case FeedbackType.WaitInvoke: { @@ -471,10 +466,10 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } default: - return default; + return returnType.GetDefault(); } } finally @@ -712,7 +707,7 @@ namespace TouchSocket.Dmtp.Rpc case FeedbackType.OnlySend: { this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); - return default; + return returnType.GetDefault(); } case FeedbackType.WaitSend: { @@ -724,7 +719,7 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } case FeedbackType.WaitInvoke: { @@ -742,11 +737,11 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } default: - return default; + return returnType.GetDefault(); } } finally @@ -757,21 +752,178 @@ namespace TouchSocket.Dmtp.Rpc } /// - public Task InvokeAsync(string invokeKey, IInvokeOption invokeOption, params object[] parameters) + public async Task InvokeAsync(string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - return Task.Run(() => + var rpcPackage = new DmtpRpcPackage { - this.Invoke(invokeKey, invokeOption, parameters); - }); + MethodName = invokeKey, + SourceId = this.DmtpActor.Id + }; + + var waitData = this.DmtpActor.WaitHandlePool.GetWaitDataAsync(rpcPackage); + var byteBlock = new ByteBlock(); + if (invokeOption == default) + { + invokeOption = DmtpInvokeOption.WaitInvoke; + } + + if (invokeOption.Token.CanBeCanceled) + { + waitData.SetCancellationToken(invokeOption.Token); + invokeOption.Token.Register(this.CanceledInvoke, new CanceledPackage() { SourceId = this.DmtpActor.Id, Sign = rpcPackage.Sign }); + } + + try + { + rpcPackage.LoadInvokeOption(invokeOption); + if (parameters != null) + { + var datas = new List(); + foreach (var parameter in parameters) + { + datas.Add(this.SerializationSelector.SerializeParameter(rpcPackage.SerializationType, parameter)); + } + rpcPackage.ParametersBytes = datas; + } + + rpcPackage.Package(byteBlock); + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + } + break; + + case FeedbackType.WaitSend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + break; + + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + break; + } + case FeedbackType.WaitInvoke: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + { + var resultContext = (DmtpRpcPackage)waitData.WaitResult; + resultContext.ThrowStatus(); + break; + } + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + break; + } + default: + break; + } + } + finally + { + this.DmtpActor.WaitHandlePool.Destroy(waitData); + byteBlock.Dispose(); + } } /// - public Task InvokeAsync(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) + public async Task InvokeAsync(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - return Task.Run(() => + var rpcPackage = new DmtpRpcPackage { - return this.Invoke(returnType,invokeKey, invokeOption, parameters); - }); + MethodName = invokeKey, + SourceId = this.DmtpActor.Id + }; + + var waitData = this.DmtpActor.WaitHandlePool.GetWaitDataAsync(rpcPackage); + var byteBlock = new ByteBlock(); + if (invokeOption == default) + { + invokeOption = DmtpInvokeOption.WaitInvoke; + } + + if (invokeOption.Token.CanBeCanceled) + { + waitData.SetCancellationToken(invokeOption.Token); + invokeOption.Token.Register(this.CanceledInvoke, new CanceledPackage() { SourceId = this.DmtpActor.Id, Sign = rpcPackage.Sign }); + } + + try + { + rpcPackage.LoadInvokeOption(invokeOption); + if (parameters != null) + { + var datas = new List(); + foreach (var parameter in parameters) + { + datas.Add(this.SerializationSelector.SerializeParameter(rpcPackage.SerializationType, parameter)); + } + rpcPackage.ParametersBytes = datas; + } + + rpcPackage.Package(byteBlock); + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + return returnType.GetDefault(); + } + case FeedbackType.WaitSend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + return returnType.GetDefault(); + } + case FeedbackType.WaitInvoke: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + { + var resultContext = (DmtpRpcPackage)waitData.WaitResult; + resultContext.ThrowStatus(); + return this.SerializationSelector.DeserializeParameter(resultContext.SerializationType, resultContext.ReturnParameterBytes, returnType); + } + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + return returnType.GetDefault(); + } + + default: + return returnType.GetDefault(); + } + } + finally + { + this.DmtpActor.WaitHandlePool.Destroy(waitData); + byteBlock.Dispose(); + } } #endregion Rpc @@ -791,7 +943,7 @@ namespace TouchSocket.Dmtp.Rpc throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); } - if (this.DmtpActor.AllowRoute&& this.TryFindDmtpRpcActor(targetId, out var actor)) + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var actor)) { actor.Invoke(invokeKey, invokeOption, parameters); return; @@ -898,9 +1050,9 @@ namespace TouchSocket.Dmtp.Rpc throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); } - if (this.DmtpActor.AllowRoute&& this.TryFindDmtpRpcActor(targetId, out var rpcActor)) + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var rpcActor)) { - return rpcActor.Invoke(returnType,invokeKey, invokeOption, parameters); + return rpcActor.Invoke(returnType, invokeKey, invokeOption, parameters); } var rpcPackage = new DmtpRpcPackage @@ -944,7 +1096,7 @@ namespace TouchSocket.Dmtp.Rpc case FeedbackType.OnlySend: { this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); - return default; + return returnType.GetDefault(); } case FeedbackType.WaitSend: { @@ -956,7 +1108,7 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } case FeedbackType.WaitInvoke: { @@ -974,11 +1126,11 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } default: - return default; + return returnType.GetDefault(); } } finally @@ -1001,7 +1153,7 @@ namespace TouchSocket.Dmtp.Rpc throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); } - if (this.DmtpActor.AllowRoute&& this.TryFindDmtpRpcActor(targetId, out var rpcActor)) + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var rpcActor)) { rpcActor.Invoke(invokeKey, invokeOption, ref parameters, types); return; @@ -1100,7 +1252,7 @@ namespace TouchSocket.Dmtp.Rpc } /// - public object Invoke(Type returnType,string targetId, string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + public object Invoke(Type returnType, string targetId, string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) { if (string.IsNullOrEmpty(targetId)) { @@ -1112,9 +1264,9 @@ namespace TouchSocket.Dmtp.Rpc throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); } - if (this.DmtpActor.AllowRoute&& this.TryFindDmtpRpcActor(targetId, out var rpcActor)) + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var rpcActor)) { - return rpcActor.Invoke(returnType,invokeKey, invokeOption, ref parameters, types); + return rpcActor.Invoke(returnType, invokeKey, invokeOption, ref parameters, types); } var rpcPackage = new DmtpRpcPackage @@ -1154,7 +1306,7 @@ namespace TouchSocket.Dmtp.Rpc case FeedbackType.OnlySend: { this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); - return default; + return returnType.GetDefault(); } case FeedbackType.WaitSend: { @@ -1166,7 +1318,7 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } case FeedbackType.WaitInvoke: { @@ -1195,11 +1347,11 @@ namespace TouchSocket.Dmtp.Rpc throw new TimeoutException("等待结果超时"); } } - return default; + return returnType.GetDefault(); } default: - return default; + return returnType.GetDefault(); } } finally @@ -1210,21 +1362,213 @@ namespace TouchSocket.Dmtp.Rpc } /// - public Task InvokeAsync(string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters) + public async Task InvokeAsync(string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - return Task.Run(() => + if (string.IsNullOrEmpty(targetId)) { - this.Invoke(targetId, invokeKey, invokeOption, parameters); - }); + throw new ArgumentException($"“{nameof(targetId)}”不能为 null 或空。", nameof(targetId)); + } + + if (string.IsNullOrEmpty(invokeKey)) + { + throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); + } + + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var actor)) + { + await actor.InvokeAsync(invokeKey, invokeOption, parameters); + return; + } + + var rpcPackage = new DmtpRpcPackage + { + MethodName = invokeKey, + Route = true, + TargetId = targetId, + SourceId = this.DmtpActor.Id, + }; + + var waitData = this.DmtpActor.WaitHandlePool.GetReverseWaitDataAsync(rpcPackage); + var byteBlock = new ByteBlock(); + if (invokeOption == default) + { + invokeOption = DmtpInvokeOption.WaitInvoke; + } + + if (invokeOption.Token.CanBeCanceled) + { + waitData.SetCancellationToken(invokeOption.Token); + invokeOption.Token.Register(this.CanceledInvoke, new CanceledPackage() { SourceId = this.DmtpActor.Id, TargetId = targetId, Sign = rpcPackage.Sign, Route = true }); + } + + try + { + rpcPackage.LoadInvokeOption(invokeOption); + if (parameters != null) + { + var datas = new List(); + foreach (var parameter in parameters) + { + datas.Add(this.SerializationSelector.SerializeParameter(rpcPackage.SerializationType, parameter)); + } + rpcPackage.ParametersBytes = datas; + } + + rpcPackage.Package(byteBlock); + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + } + break; + + case FeedbackType.WaitSend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + break; + + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + break; + } + case FeedbackType.WaitInvoke: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + { + var resultContext = (DmtpRpcPackage)waitData.WaitResult; + resultContext.ThrowStatus(); + break; + } + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + break; + } + default: + break; + } + } + finally + { + this.DmtpActor.WaitHandlePool.Destroy(waitData); + byteBlock.Dispose(); + } } /// - public Task InvokeAsync(Type returnType, string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters) + public async Task InvokeAsync(Type returnType, string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - return Task.Run(() => + if (string.IsNullOrEmpty(targetId)) { - return this.Invoke(returnType,targetId, invokeKey, invokeOption, parameters); - }); + throw new ArgumentException($"“{nameof(targetId)}”不能为 null 或空。", nameof(targetId)); + } + + if (string.IsNullOrEmpty(invokeKey)) + { + throw new ArgumentException($"“{nameof(invokeKey)}”不能为 null 或空。", nameof(invokeKey)); + } + + if (this.DmtpActor.AllowRoute && this.TryFindDmtpRpcActor(targetId, out var rpcActor)) + { + return await rpcActor.InvokeAsync(returnType, invokeKey, invokeOption, parameters); + } + + var rpcPackage = new DmtpRpcPackage + { + MethodName = invokeKey, + TargetId = targetId, + SourceId = this.DmtpActor.Id, + Route = true + }; + + var waitData = this.DmtpActor.WaitHandlePool.GetReverseWaitDataAsync(rpcPackage); + var byteBlock = new ByteBlock(); + if (invokeOption == default) + { + invokeOption = DmtpInvokeOption.WaitInvoke; + } + + if (invokeOption.Token.CanBeCanceled) + { + waitData.SetCancellationToken(invokeOption.Token); + invokeOption.Token.Register(this.CanceledInvoke, new CanceledPackage() { SourceId = this.DmtpActor.Id, TargetId = targetId, Sign = rpcPackage.Sign, Route = true }); + } + + try + { + rpcPackage.LoadInvokeOption(invokeOption); + if (parameters != null) + { + var datas = new List(); + foreach (var parameter in parameters) + { + datas.Add(this.SerializationSelector.SerializeParameter(rpcPackage.SerializationType, parameter)); + } + rpcPackage.ParametersBytes = datas; + } + + rpcPackage.Package(byteBlock); + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + return returnType.GetDefault(); + } + case FeedbackType.WaitSend: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + return returnType.GetDefault(); + } + case FeedbackType.WaitInvoke: + { + this.DmtpActor.Send(this.m_invoke_Request, byteBlock.Buffer, 0, byteBlock.Len); + switch (await waitData.WaitAsync(invokeOption.Timeout)) + { + case WaitDataStatus.SetRunning: + { + var resultContext = (DmtpRpcPackage)waitData.WaitResult; + resultContext.ThrowStatus(); + return this.SerializationSelector.DeserializeParameter(resultContext.SerializationType, resultContext.ReturnParameterBytes, returnType); + } + case WaitDataStatus.Overtime: + { + throw new TimeoutException("等待结果超时"); + } + } + return returnType.GetDefault(); + } + + default: + return returnType.GetDefault(); + } + } + finally + { + this.DmtpActor.WaitHandlePool.Destroy(waitData); + byteBlock.Dispose(); + } } #endregion IdRpc diff --git a/src/TouchSocket.Dmtp/Features/Rpc/Actor/ITargetDmtpRpcActor.cs b/src/TouchSocket.Dmtp/Features/Rpc/Actor/TargetDmtpRpcActor.cs similarity index 94% rename from src/TouchSocket.Dmtp/Features/Rpc/Actor/ITargetDmtpRpcActor.cs rename to src/TouchSocket.Dmtp/Features/Rpc/Actor/TargetDmtpRpcActor.cs index 637ff60b4..d50136b13 100644 --- a/src/TouchSocket.Dmtp/Features/Rpc/Actor/ITargetDmtpRpcActor.cs +++ b/src/TouchSocket.Dmtp/Features/Rpc/Actor/TargetDmtpRpcActor.cs @@ -17,9 +17,9 @@ using TouchSocket.Rpc; namespace TouchSocket.Dmtp.Rpc { /// - /// ITargetDmtpRpcActor + /// TargetDmtpRpcActor /// - internal class ITargetDmtpRpcActor : IRpcClient + internal class TargetDmtpRpcActor : IRpcClient { private readonly IDmtpRpcActor m_rpcActor; private readonly string m_targetId; @@ -29,7 +29,7 @@ namespace TouchSocket.Dmtp.Rpc /// /// /// - public ITargetDmtpRpcActor(string targetId, IDmtpRpcActor rpcActor) + public TargetDmtpRpcActor(string targetId, IDmtpRpcActor rpcActor) { this.m_targetId = targetId; this.m_rpcActor = rpcActor; diff --git a/src/TouchSocket.Dmtp/Features/Rpc/CanceledPackage.cs b/src/TouchSocket.Dmtp/Features/Rpc/CanceledPackage.cs index bbd766236..68156524f 100644 --- a/src/TouchSocket.Dmtp/Features/Rpc/CanceledPackage.cs +++ b/src/TouchSocket.Dmtp/Features/Rpc/CanceledPackage.cs @@ -19,12 +19,12 @@ namespace TouchSocket.Dmtp.Rpc { public long Sign { get; set; } - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { byteBlock.Write(this.Sign); } - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { this.Sign = byteBlock.ReadInt64(); } diff --git a/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcActorExtension.cs b/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcActorExtension.cs index 9efc69765..9d54e68cc 100644 --- a/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcActorExtension.cs +++ b/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcActorExtension.cs @@ -1,5 +1,4 @@ using System; -using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Resources; using TouchSocket.Rpc; @@ -26,9 +25,9 @@ namespace TouchSocket.Dmtp.Rpc /// /// /// - public static IRpcClient CreateIdRpcClient(this IDmtpActorObject client, string targetId) + public static IRpcClient CreateTargetDmtpRpcActor(this IDmtpActorObject client, string targetId) { - return new ITargetDmtpRpcActor(targetId, client.GetDmtpRpcActor()); + return new TargetDmtpRpcActor(targetId, client.GetDmtpRpcActor()); } /// @@ -63,7 +62,7 @@ namespace TouchSocket.Dmtp.Rpc /// /// /// - public static TDmtpRpcActor GetDmtpRpcActor(this IDmtpActorObject client)where TDmtpRpcActor : IDmtpRpcActor + public static TDmtpRpcActor GetDmtpRpcActor(this IDmtpActorObject client) where TDmtpRpcActor : IDmtpRpcActor { var smtpRpcActor = client.DmtpActor.GetDmtpRpcActor(); if (smtpRpcActor is null) @@ -100,7 +99,7 @@ namespace TouchSocket.Dmtp.Rpc /// /// /// - public static DmtpRpcFeature UseDmtpRpc(this IPluginsManager pluginsManager)where TDmtpRpcFeature: DmtpRpcFeature + public static DmtpRpcFeature UseDmtpRpc(this IPluginsManager pluginsManager) where TDmtpRpcFeature : DmtpRpcFeature { return pluginsManager.Add(); } diff --git a/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcPackage.cs b/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcPackage.cs index 445f91e8b..5c573ab5b 100644 --- a/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcPackage.cs +++ b/src/TouchSocket.Dmtp/Features/Rpc/DmtpRpcPackage.cs @@ -23,6 +23,9 @@ namespace TouchSocket.Dmtp.Rpc /// public sealed class DmtpRpcPackage : WaitRouterPackage { + /// + protected override bool IncludedRouter => true; + /// /// 反馈类型 /// @@ -54,7 +57,7 @@ namespace TouchSocket.Dmtp.Rpc public SerializationType SerializationType { get; private set; } /// - public override void PackageBody(ByteBlock byteBlock) + public override void PackageBody(in ByteBlock byteBlock) { base.PackageBody(byteBlock); byteBlock.Write((byte)this.SerializationType); @@ -78,7 +81,7 @@ namespace TouchSocket.Dmtp.Rpc } /// - public override void UnpackageBody(ByteBlock byteBlock) + public override void UnpackageBody(in ByteBlock byteBlock) { base.UnpackageBody(byteBlock); this.SerializationType = (SerializationType)byteBlock.ReadByte(); diff --git a/src/TouchSocket.Dmtp/Interfaces/IDmtpActorObject.cs b/src/TouchSocket.Dmtp/Interfaces/IDmtpActorObject.cs index 045b2d7cb..ad62bfd84 100644 --- a/src/TouchSocket.Dmtp/Interfaces/IDmtpActorObject.cs +++ b/src/TouchSocket.Dmtp/Interfaces/IDmtpActorObject.cs @@ -1,6 +1,4 @@ -using System.Threading.Tasks; - -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp { /// /// 定义包含成员的接口对象。 diff --git a/src/TouchSocket.Dmtp/Interfaces/IDmtpFeature.cs b/src/TouchSocket.Dmtp/Interfaces/IDmtpFeature.cs index d8b338da4..3caf0cfd2 100644 --- a/src/TouchSocket.Dmtp/Interfaces/IDmtpFeature.cs +++ b/src/TouchSocket.Dmtp/Interfaces/IDmtpFeature.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp { /// /// Dmtp功能性组件接口 diff --git a/src/TouchSocket.Dmtp/Plugins/DmtpHeartbeatPlugin.cs b/src/TouchSocket.Dmtp/Plugins/DmtpHeartbeatPlugin.cs index 10ba8641d..289354992 100644 --- a/src/TouchSocket.Dmtp/Plugins/DmtpHeartbeatPlugin.cs +++ b/src/TouchSocket.Dmtp/Plugins/DmtpHeartbeatPlugin.cs @@ -13,6 +13,7 @@ using System; using System.Threading.Tasks; using TouchSocket.Core; +using TouchSocket.Sockets; namespace TouchSocket.Dmtp { @@ -20,44 +21,11 @@ namespace TouchSocket.Dmtp /// 基于Dmtp的心跳插件。服务器和客户端均适用 /// [PluginOption(Singleton = true, NotRegister = true)] - public class DmtpHeartbeatPlugin : PluginBase, IDmtpHandshakedPlugin where TClient : IDmtpActorObject + public class DmtpHeartbeatPlugin : HeartbeatPlugin, IDmtpHandshakedPlugin { - /// - /// 最大失败次数,默认3。 - /// - public int MaxFailCount { get; set; } = 3; - - /// - /// 心跳间隔。默认3秒。 - /// - public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(3); - - - /// - /// 最大失败次数,默认3。 - /// - /// - /// - public DmtpHeartbeatPlugin SetMaxFailCount(int value) + Task IDmtpHandshakedPlugin.OnDmtpHandshaked(IDmtpActorObject client, DmtpVerifyEventArgs e) { - this.MaxFailCount = value; - return this; - } - - /// - /// 心跳间隔。默认3秒。 - /// - /// - /// - public DmtpHeartbeatPlugin SetTick(TimeSpan value) - { - this.Tick = value; - return this; - } - - Task IDmtpHandshakedPlugin.OnDmtpHandshaked(TClient client, DmtpVerifyEventArgs e) - { - Task.Run(async() => + Task.Run(async () => { var failedCount = 0; while (true) diff --git a/src/TouchSocket.Dmtp/Plugins/IDmtpCreateChannelPlugin.cs b/src/TouchSocket.Dmtp/Plugins/IDmtpCreateChannelPlugin.cs index 75b097545..185685e45 100644 --- a/src/TouchSocket.Dmtp/Plugins/IDmtpCreateChannelPlugin.cs +++ b/src/TouchSocket.Dmtp/Plugins/IDmtpCreateChannelPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Dmtp diff --git a/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakedPlugin.cs b/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakedPlugin.cs index fd50e4ef1..16ac5f12f 100644 --- a/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakedPlugin.cs +++ b/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakedPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Dmtp @@ -11,7 +7,7 @@ namespace TouchSocket.Dmtp /// IDmtpHandshakedPlugin /// /// - public interface IDmtpHandshakedPlugin:IPlugin where TClient : IDmtpActorObject + public interface IDmtpHandshakedPlugin : IPlugin where TClient : IDmtpActorObject { /// /// 在完成握手连接时。 @@ -25,8 +21,8 @@ namespace TouchSocket.Dmtp /// /// IDmtpHandshakedPlugin /// - public interface IDmtpHandshakedPlugin: IDmtpHandshakedPlugin - { - + public interface IDmtpHandshakedPlugin : IDmtpHandshakedPlugin + { + } } diff --git a/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakingPlugin.cs b/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakingPlugin.cs index 18b4e1cf1..0625a78ce 100644 --- a/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakingPlugin.cs +++ b/src/TouchSocket.Dmtp/Plugins/IDmtpHandshakingPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Dmtp @@ -11,7 +7,7 @@ namespace TouchSocket.Dmtp /// IDmtpHandshakedPlugin /// /// - public interface IDmtpHandshakingPlugin:IPlugin where TClient : IDmtpActorObject + public interface IDmtpHandshakingPlugin : IPlugin where TClient : IDmtpActorObject { /// /// 在验证Token时 diff --git a/src/TouchSocket.Dmtp/Plugins/IDmtpRoutingPlugin.cs b/src/TouchSocket.Dmtp/Plugins/IDmtpRoutingPlugin.cs index 2dcd35658..2a29bc577 100644 --- a/src/TouchSocket.Dmtp/Plugins/IDmtpRoutingPlugin.cs +++ b/src/TouchSocket.Dmtp/Plugins/IDmtpRoutingPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Dmtp @@ -11,7 +7,7 @@ namespace TouchSocket.Dmtp /// IDmtpRoutingPlugin /// /// - public interface IDmtpRoutingPlugin:IPlugin where TClient: IDmtpActorObject + public interface IDmtpRoutingPlugin : IPlugin where TClient : IDmtpActorObject { /// /// 当需要转发路由包时 diff --git a/src/TouchSocket.Dmtp/ProtocolSecure/IProtocolSecureService.cs b/src/TouchSocket.Dmtp/ProtocolSecure/IProtocolSecureService.cs index 1bb183826..a24c50697 100644 --- a/src/TouchSocket.Dmtp/ProtocolSecure/IProtocolSecureService.cs +++ b/src/TouchSocket.Dmtp/ProtocolSecure/IProtocolSecureService.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TouchSocket.Dmtp +namespace TouchSocket.Dmtp { /// /// 协议安全服务,主要用于检测协议冲突的问题。 diff --git a/src/TouchSocket.Dmtp/ProtocolSecure/ProtocolSecureService.cs b/src/TouchSocket.Dmtp/ProtocolSecure/ProtocolSecureService.cs index 37a49e8b3..188318ae4 100644 --- a/src/TouchSocket.Dmtp/ProtocolSecure/ProtocolSecureService.cs +++ b/src/TouchSocket.Dmtp/ProtocolSecure/ProtocolSecureService.cs @@ -1,18 +1,13 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace TouchSocket.Dmtp { - internal class ProtocolSecureService: IProtocolSecureService + internal class ProtocolSecureService : IProtocolSecureService { - readonly Dictionary m_dic=new Dictionary(); - public void RegisterProtocol(ushort protocol,string description) - { - + readonly Dictionary m_dic = new Dictionary(); + public void RegisterProtocol(ushort protocol, string description) + { + } } } diff --git a/src/TouchSocket.Dmtp/Resources/TouchSocketDmtpStatus.cs b/src/TouchSocket.Dmtp/Resources/TouchSocketDmtpStatus.cs index f310a49d6..ec5cc0e80 100644 --- a/src/TouchSocket.Dmtp/Resources/TouchSocketDmtpStatus.cs +++ b/src/TouchSocket.Dmtp/Resources/TouchSocketDmtpStatus.cs @@ -49,6 +49,7 @@ namespace TouchSocket.Resources /// [Description("发生异常,信息:{0}。")] Exception, + /// /// 不允许路由该包,信息:{0}。 /// @@ -121,8 +122,6 @@ namespace TouchSocket.Resources [Description("路径‘{0}’对应的流文件,仍然被‘{1}’对象应用。")] StreamReferencing, - - /// /// 从‘{0}’路径加载流异常,信息:‘{1}’。 /// @@ -193,6 +192,12 @@ namespace TouchSocket.Resources /// 没有找到任何可用的目标Id。 /// [Description("没有找到任何可用的目标Id。")] - NotFindAnyTargetId + NotFindAnyTargetId, + + /// + /// 响应方不支持路由操作。 + /// + [Description("响应方不支持路由操作。")] + RoutingNotSupported, } } \ No newline at end of file diff --git a/src/TouchSocket.Dmtp/Services/Route/DmtpRouteService.cs b/src/TouchSocket.Dmtp/Services/Route/DmtpRouteService.cs index e228e6714..a0f5f319c 100644 --- a/src/TouchSocket.Dmtp/Services/Route/DmtpRouteService.cs +++ b/src/TouchSocket.Dmtp/Services/Route/DmtpRouteService.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Sockets; namespace TouchSocket.Dmtp { diff --git a/src/TouchSocket.Dmtp/Services/Route/DmtpRouteServiceExtension.cs b/src/TouchSocket.Dmtp/Services/Route/DmtpRouteServiceExtension.cs index 8dd130357..aeab69f05 100644 --- a/src/TouchSocket.Dmtp/Services/Route/DmtpRouteServiceExtension.cs +++ b/src/TouchSocket.Dmtp/Services/Route/DmtpRouteServiceExtension.cs @@ -1,6 +1,5 @@ using System; using TouchSocket.Core; -using TouchSocket.Dmtp; namespace TouchSocket.Dmtp { @@ -10,7 +9,7 @@ namespace TouchSocket.Dmtp public static class DmtpRouteServiceExtension { /// - /// 添加基于Tcp服务器的Dmtp路由服务。 + /// 添加Dmtp路由服务。 /// /// public static void AddDmtpRouteService(this IContainer container) diff --git a/src/TouchSocket.Dmtp/Services/Route/IDmtpRouteService.cs b/src/TouchSocket.Dmtp/Services/Route/IDmtpRouteService.cs index 8c8678d7a..5a83eb27b 100644 --- a/src/TouchSocket.Dmtp/Services/Route/IDmtpRouteService.cs +++ b/src/TouchSocket.Dmtp/Services/Route/IDmtpRouteService.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace TouchSocket.Dmtp { diff --git a/src/TouchSocket.Dmtp/TouchSocket.Dmtp.csproj b/src/TouchSocket.Dmtp/TouchSocket.Dmtp.csproj index d2012cb19..03ea16eac 100644 --- a/src/TouchSocket.Dmtp/TouchSocket.Dmtp.csproj +++ b/src/TouchSocket.Dmtp/TouchSocket.Dmtp.csproj @@ -1,54 +1,22 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta.1 - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 message;duplex;rpc;filetransfer;redis 这是基于TouchSocket的,实现自主数据的全双工通信协议。能够非常简单的实现跨语言连接等。 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt TouchSocket.Dmtp - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.Dmtp + ..\..\Build\NugetPackages\TouchSocket.Dmtp - + - - True - - - - True - - - - - - - - - - - - + + + True + Embedded + True + diff --git a/src/TouchSocket.Http/Common/HttpBase.cs b/src/TouchSocket.Http/Common/HttpBase.cs index d7d64a834..f4347c282 100644 --- a/src/TouchSocket.Http/Common/HttpBase.cs +++ b/src/TouchSocket.Http/Common/HttpBase.cs @@ -77,16 +77,26 @@ namespace TouchSocket.Http } return 0; } - set + set { - this.m_headers.Add(HttpHeaders.ContentLength,value.ToString()); + this.m_headers.Add(HttpHeaders.ContentLength, value.ToString()); } } /// /// 内容类型 /// - public string ContentType { get; set; } + public string ContentType + { + get + { + return this.m_headers.Get(HttpHeaders.ContentType); + } + set + { + this.m_headers.Add(HttpHeaders.ContentType, value); + } + } /// /// 传递标识 @@ -233,8 +243,6 @@ namespace TouchSocket.Http this.Headers.Add(key, kv[1]); } } - - this.ContentType = this.Headers.Get(HttpHeaders.ContentType); } } } \ No newline at end of file diff --git a/src/TouchSocket.Http/Common/HttpMethod.cs b/src/TouchSocket.Http/Common/HttpMethod.cs index 7505f6548..322917def 100644 --- a/src/TouchSocket.Http/Common/HttpMethod.cs +++ b/src/TouchSocket.Http/Common/HttpMethod.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Sockets; namespace TouchSocket.Http { @@ -20,7 +15,7 @@ namespace TouchSocket.Http /// /// Get /// - public static readonly HttpMethod Get= new HttpMethod("get"); + public static readonly HttpMethod Get = new HttpMethod("get"); /// /// Post @@ -65,7 +60,7 @@ namespace TouchSocket.Http /// public override int GetHashCode() { - return this.m_value.GetHashCode(); + return this.m_value.GetHashCode(); } /// @@ -86,7 +81,7 @@ namespace TouchSocket.Http /// public static bool operator ==(HttpMethod a, HttpMethod b) { - return string.IsNullOrEmpty(a.m_value) && string.IsNullOrEmpty(b.m_value)|| string.Equals(a.m_value, b.m_value, StringComparison.OrdinalIgnoreCase); + return string.IsNullOrEmpty(a.m_value) && string.IsNullOrEmpty(b.m_value) || string.Equals(a.m_value, b.m_value, StringComparison.OrdinalIgnoreCase); } /// diff --git a/src/TouchSocket.Http/Common/HttpRequest.cs b/src/TouchSocket.Http/Common/HttpRequest.cs index aa07814da..0c06d3fb8 100644 --- a/src/TouchSocket.Http/Common/HttpRequest.cs +++ b/src/TouchSocket.Http/Common/HttpRequest.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; -using System.Collections.Specialized; using System.IO; using System.Linq; using System.Text; @@ -29,9 +28,9 @@ namespace TouchSocket.Http private bool m_canRead; private ITcpClientBase m_client; private byte[] m_content; - private NameValueCollection m_forms; - private NameValueCollection m_params; - private NameValueCollection m_query; + private InternalHttpParams m_forms; + private InternalHttpParams m_params; + private InternalHttpParams m_query; private bool m_sentHeader; private int m_sentLength; @@ -82,17 +81,17 @@ namespace TouchSocket.Http /// /// 表单数据 /// - public NameValueCollection Forms + public IHttpParams Forms { get { if (this.ContentType == @"application/x-www-form-urlencoded") { - this.m_forms ??= this.GetParameters(this.GetBody()); + this.m_forms ??= GetParameters(this.GetBody()); return this.m_forms; } - return this.m_forms ??= new NameValueCollection(); + return this.m_forms ??= new InternalHttpParams(); } } @@ -115,11 +114,11 @@ namespace TouchSocket.Http /// /// Body参数 /// - public NameValueCollection Params + public IHttpParams Params { get { - this.m_params ??= new NameValueCollection(); + this.m_params ??= new InternalHttpParams(); return this.m_params; } } @@ -127,11 +126,11 @@ namespace TouchSocket.Http /// /// url参数 /// - public NameValueCollection Query + public IHttpParams Query { get { - this.m_query ??= new NameValueCollection(); + this.m_query ??= new InternalHttpParams(); return this.m_query; } } @@ -305,7 +304,7 @@ namespace TouchSocket.Http protected override void LoadHeaderProterties() { var first = Regex.Split(this.RequestLine, @"(\s+)").Where(e => e.Trim() != string.Empty).ToArray(); - if (first.Length > 0) this.Method =new HttpMethod(first[0].Trim()); + if (first.Length > 0) this.Method = new HttpMethod(first[0].Trim()); if (first.Length > 1) { this.SetUrl(Uri.UnescapeDataString(first[1])); @@ -315,7 +314,7 @@ namespace TouchSocket.Http var ps = first[2].Split('/'); if (ps.Length == 2) { - this.Protocols =new Protocol(ps[0]) ; + this.Protocols = new Protocol(ps[0]); this.ProtocolVersion = ps[1]; } } @@ -348,14 +347,14 @@ namespace TouchSocket.Http { var urlBuilder = new StringBuilder(); urlBuilder.Append(this.RelativeURL); - urlBuilder.Append("?"); + urlBuilder.Append('?'); var i = 0; - foreach (var item in this.m_query.AllKeys) + foreach (var item in this.m_query.Keys) { urlBuilder.Append($"{item}={this.m_query[item]}"); if (++i < this.m_query.Count) { - urlBuilder.Append("&"); + urlBuilder.Append('&'); } } url = urlBuilder.ToString(); @@ -370,7 +369,7 @@ namespace TouchSocket.Http { stringBuilder.Append($"{this.Method} {url} HTTP/{this.ProtocolVersion}\r\n"); } - + foreach (var headerkey in this.Headers.Keys) { stringBuilder.Append($"{headerkey}: "); @@ -381,7 +380,7 @@ namespace TouchSocket.Http byteBlock.Write(Encoding.UTF8.GetBytes(stringBuilder.ToString())); } - private NameValueCollection GetParameters(string row) + private static InternalHttpParams GetParameters(string row) { if (string.IsNullOrEmpty(row)) { @@ -393,7 +392,7 @@ namespace TouchSocket.Http return null; } - var pairs = new NameValueCollection(); + var pairs = new InternalHttpParams(); foreach (var item in kvs) { var kv = item.SplitFirst('='); @@ -417,7 +416,7 @@ namespace TouchSocket.Http } if (urls.Length > 1) { - this.m_query = this.GetParameters(urls[1]); + this.m_query = GetParameters(urls[1]); } } else diff --git a/src/TouchSocket.Http/Common/HttpResponse.cs b/src/TouchSocket.Http/Common/HttpResponse.cs index 8c4ded67e..7ce0a7a92 100644 --- a/src/TouchSocket.Http/Common/HttpResponse.cs +++ b/src/TouchSocket.Http/Common/HttpResponse.cs @@ -98,7 +98,7 @@ namespace TouchSocket.Http { get { - return this.StatusCode == "407"; + return this.StatusCode == 407; } } @@ -109,7 +109,7 @@ namespace TouchSocket.Http { get { - return this.StatusCode == "301" || this.StatusCode == "302"; + return this.StatusCode == 301 || this.StatusCode == 302; } } @@ -121,7 +121,7 @@ namespace TouchSocket.Http /// /// 状态码,默认200 /// - public string StatusCode { get; set; } = "200"; + public int StatusCode { get; set; } = 200; /// /// 状态消息,默认Success @@ -344,13 +344,14 @@ namespace TouchSocket.Http var ps = first[0].Split('/'); if (ps.Length == 2) { - this.Protocols =new Protocol(ps[0]) ; + this.Protocols = new Protocol(ps[0]); this.ProtocolVersion = ps[1]; } } if (first.Length > 1) { - this.StatusCode = first[1]; + int.TryParse(first[1], out var code); + this.StatusCode = code; } var msg = string.Empty; for (var i = 2; i < first.Length; i++) diff --git a/src/TouchSocket.Http/Common/Internal/InternalHttpHeader.cs b/src/TouchSocket.Http/Common/Internal/InternalHttpHeader.cs index d5dddb4c2..15c691747 100644 --- a/src/TouchSocket.Http/Common/Internal/InternalHttpHeader.cs +++ b/src/TouchSocket.Http/Common/Internal/InternalHttpHeader.cs @@ -1,10 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Http @@ -61,7 +56,7 @@ namespace TouchSocket.Http public new void Add(string key, string value) { - if (key == null) + if (key == null) { return; } diff --git a/src/TouchSocket.Http/Common/Internal/InternalHttpParams.cs b/src/TouchSocket.Http/Common/Internal/InternalHttpParams.cs new file mode 100644 index 000000000..dca25ef10 --- /dev/null +++ b/src/TouchSocket.Http/Common/Internal/InternalHttpParams.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using TouchSocket.Core; + +namespace TouchSocket.Http +{ + internal class InternalHttpParams : Dictionary, IHttpParams + { + public InternalHttpParams() : base(StringComparer.OrdinalIgnoreCase) + { + + } + + public new string this[string key] + { + get + { + if (key == null) + { + return null; + } + if (this.TryGetValue(key, out var value)) + { + return value; + } + return null; + } + + set + { + if (key == null) + { + return; + } + + this.AddOrUpdate(key, value); + } + } + + + + public new void Add(string key, string value) + { + if (key == null) + { + return; + } + this.AddOrUpdate(key, value); + } + + public string Get(string key) + { + if (key == null) + { + return null; + } + if (this.TryGetValue(key, out var value)) + { + return value; + } + return null; + } + } +} diff --git a/src/TouchSocket.Http/Components/HttpClient.cs b/src/TouchSocket.Http/Components/HttpClient.cs index 4dda24b11..6c19c72af 100644 --- a/src/TouchSocket.Http/Components/HttpClient.cs +++ b/src/TouchSocket.Http/Components/HttpClient.cs @@ -31,8 +31,8 @@ namespace TouchSocket.Http public class HttpClientBase : TcpClientBase, IHttpClient { private readonly object m_requestLocker = new object(); - private bool m_getContent; private readonly WaitData m_waitData; + private bool m_getContent; /// /// 构造函数 @@ -42,6 +42,69 @@ namespace TouchSocket.Http this.m_waitData = new WaitData(); } + /// + /// + /// + /// + /// + public override ITcpClient Connect(int timeout = 5000) + { + if (this.Config.GetValue(HttpConfigExtensions.HttpProxyProperty) is HttpProxy httpProxy) + { + var proxyHost = httpProxy.Host; + var credential = httpProxy.Credential; + var remoteHost = this.Config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty); + try + { + this.Config.SetRemoteIPHost(proxyHost); + base.Connect(timeout); + var request = new HttpRequest(); + request.InitHeaders() + .SetHost(remoteHost.Host) + .SetUrl(remoteHost.Host, true) + .AsMethod("CONNECT"); + var response = this.Request(request, timeout: timeout); + if (response.IsProxyAuthenticationRequired) + { + if (credential is null) + { + throw new Exception("未指定代理的凭据。"); + } + var authHeader = response.Headers.Get(HttpHeaders.ProxyAuthenticate); + if (authHeader.IsNullOrEmpty()) + { + throw new Exception("未指定代理身份验证质询。"); + } + + var ares = new AuthenticationChallenge(authHeader, credential); + + request.Headers.Add(HttpHeaders.ProxyAuthorization, ares.ToString()); + if (response.CloseConnection) + { + base.Close("代理要求关闭连接,随后重写连接。"); + base.Connect(timeout); + } + + response = this.Request(request, timeout: timeout); + } + + if (response.StatusCode != 200) + { + throw new Exception(response.StatusMessage); + } + } + finally + { + this.Config.SetRemoteIPHost(remoteHost); + } + } + else + { + base.Connect(timeout); + } + return this; + } + /// /// /// @@ -142,69 +205,6 @@ namespace TouchSocket.Http base.Dispose(disposing); } - /// - /// - /// - /// - /// - public override ITcpClient Connect(int timeout = 5000) - { - if (this.Config.GetValue(HttpConfigExtensions.HttpProxyProperty) is HttpProxy httpProxy) - { - var proxyHost = httpProxy.Host; - var credential = httpProxy.Credential; - var remoteHost = this.Config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty); - try - { - this.Config.SetRemoteIPHost(proxyHost); - base.Connect(timeout); - var request = new HttpRequest(); - request.InitHeaders() - .SetHost(remoteHost.Host) - .SetUrl(remoteHost.Host, true) - .AsMethod("CONNECT"); - var response = this.Request(request, timeout: timeout); - if (response.IsProxyAuthenticationRequired) - { - if (credential is null) - { - throw new Exception("未指定代理的凭据。"); - } - var authHeader = response.Headers.Get(HttpHeaders.ProxyAuthenticate); - if (authHeader.IsNullOrEmpty()) - { - throw new Exception("未指定代理身份验证质询。"); - } - - var ares = new AuthenticationChallenge(authHeader, credential); - - request.Headers.Add(HttpHeaders.ProxyAuthorization, ares.ToString()); - if (response.CloseConnection) - { - base.Close("代理要求关闭连接,随后重写连接。"); - base.Connect(timeout); - } - - response = this.Request(request, timeout: timeout); - } - - if (response.StatusCode != "200") - { - throw new Exception(response.StatusMessage); - } - } - finally - { - this.Config.SetRemoteIPHost(remoteHost); - } - } - else - { - base.Connect(timeout); - } - return this; - } - /// /// /// diff --git a/src/TouchSocket.Http/Components/HttpClientSlim.cs b/src/TouchSocket.Http/Components/HttpClientSlim.cs new file mode 100644 index 000000000..e639dc112 --- /dev/null +++ b/src/TouchSocket.Http/Components/HttpClientSlim.cs @@ -0,0 +1,142 @@ +#if !NET45 +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Sockets; + +namespace TouchSocket.Http +{ + /// + /// 这是基于的通讯模型。 + /// + public class HttpClientSlim : DisposableObject + { + private readonly System.Net.Http.HttpClient m_httpClient; + + /// + /// 这是基于的通讯模型。 + /// + /// + public HttpClientSlim(System.Net.Http.HttpClient httpClient = default) + { + httpClient ??= new System.Net.Http.HttpClient(); + this.m_httpClient = httpClient; + } + + /// + /// 配置 + /// + public TouchSocketConfig Config { get; private set; } + + /// + /// Ioc容器 + /// + public IContainer Container { get; private set; } + + /// + /// 插件管理器 + /// + public IPluginsManager PluginsManager { get; private set; } + + /// + /// 日志记录器 + /// + public ILog Logger { get; private set; } + + /// + /// 通讯客户端 + /// + public System.Net.Http.HttpClient HttpClient => this.m_httpClient; + + /// + /// 加载配置 + /// + /// + protected virtual void LoadConfig(TouchSocketConfig config) + { + this.m_httpClient.BaseAddress ??= config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty); + this.Logger ??= this.Container.Resolve(); + + } + + /// + /// 配置 + /// + /// + /// + /// + public HttpClientSlim Setup(TouchSocketConfig config) + { + if (config == null) + { + throw new ArgumentNullException(nameof(config)); + } + + this.ThrowIfDisposed(); + + this.BuildConfig(config); + + this.PluginsManager.Raise(nameof(ILoadingConfigPlugin.OnLoadingConfig), this, new ConfigEventArgs(config)); + this.LoadConfig(this.Config); + this.PluginsManager.Raise(nameof(ILoadedConfigPlugin.OnLoadedConfig), this, new ConfigEventArgs(config)); + + return this; + } + + /// + /// 配置 + /// + /// + /// + public HttpClientSlim Setup(string remoteIPHost) + { + return this.Setup(new TouchSocketConfig().SetRemoteIPHost(remoteIPHost)); + } + + private void BuildConfig(TouchSocketConfig config) + { + this.Config = config; + + if (!(config.GetValue(TouchSocketCoreConfigExtension.ContainerProperty) is IContainer container)) + { + container = new Container(); + } + + if (!container.IsRegistered(typeof(ILog))) + { + container.RegisterSingleton(); + } + + if (!(config.GetValue(TouchSocketCoreConfigExtension.PluginsManagerProperty) is IPluginsManager pluginsManager)) + { + pluginsManager = new PluginsManager(container); + } + + if (container.IsRegistered(typeof(IPluginsManager))) + { + pluginsManager = container.Resolve(); + } + else + { + container.RegisterSingleton(pluginsManager); + } + + if (config.GetValue(TouchSocketCoreConfigExtension.ConfigureContainerProperty) is Action actionContainer) + { + actionContainer.Invoke(container); + } + + if (config.GetValue(TouchSocketCoreConfigExtension.ConfigurePluginsProperty) is Action actionPluginsManager) + { + pluginsManager.Enable = true; + actionPluginsManager.Invoke(pluginsManager); + } + this.Container = container; + this.PluginsManager = pluginsManager; + } + } +} +#endif diff --git a/src/TouchSocket.Http/Interface/IHttpClient.cs b/src/TouchSocket.Http/Components/Interfaces/IHttpClient.cs similarity index 88% rename from src/TouchSocket.Http/Interface/IHttpClient.cs rename to src/TouchSocket.Http/Components/Interfaces/IHttpClient.cs index 26eb1727f..95a47935d 100644 --- a/src/TouchSocket.Http/Interface/IHttpClient.cs +++ b/src/TouchSocket.Http/Components/Interfaces/IHttpClient.cs @@ -15,20 +15,6 @@ using TouchSocket.Sockets; namespace TouchSocket.Http { - /// - /// Http终端基础接口 - /// - public interface IHttpClientBase : ITcpClientBase - { - } - - /// - /// Http服务器终端接口 - /// - public interface IHttpSocketClient : IHttpClientBase - { - } - /// /// Http终端接口 /// diff --git a/src/TouchSocket.Http/Components/Interfaces/IHttpClientBase.cs b/src/TouchSocket.Http/Components/Interfaces/IHttpClientBase.cs new file mode 100644 index 000000000..0f439b5c2 --- /dev/null +++ b/src/TouchSocket.Http/Components/Interfaces/IHttpClientBase.cs @@ -0,0 +1,11 @@ +using TouchSocket.Sockets; + +namespace TouchSocket.Http +{ + /// + /// Http终端基础接口 + /// + public interface IHttpClientBase : ITcpClientBase + { + } +} diff --git a/src/TouchSocket.Http/Interface/IHttpService.cs b/src/TouchSocket.Http/Components/Interfaces/IHttpService.cs similarity index 100% rename from src/TouchSocket.Http/Interface/IHttpService.cs rename to src/TouchSocket.Http/Components/Interfaces/IHttpService.cs diff --git a/src/TouchSocket.Http/Components/Interfaces/IHttpSocketClient.cs b/src/TouchSocket.Http/Components/Interfaces/IHttpSocketClient.cs new file mode 100644 index 000000000..c44a679ea --- /dev/null +++ b/src/TouchSocket.Http/Components/Interfaces/IHttpSocketClient.cs @@ -0,0 +1,11 @@ +using TouchSocket.Sockets; + +namespace TouchSocket.Http +{ + /// + /// Http服务器终端接口 + /// + public interface IHttpSocketClient : IHttpClientBase, ISocketClient + { + } +} diff --git a/src/TouchSocket.Http/DataAdapter/HttpClientDataHandlingAdapter.cs b/src/TouchSocket.Http/DataAdapter/HttpClientDataHandlingAdapter.cs index 08d77f019..6f0486194 100644 --- a/src/TouchSocket.Http/DataAdapter/HttpClientDataHandlingAdapter.cs +++ b/src/TouchSocket.Http/DataAdapter/HttpClientDataHandlingAdapter.cs @@ -113,10 +113,10 @@ namespace TouchSocket.Http private Task RunGoReceived(HttpResponse response) { - return Task.Run(() => - { - this.GoReceived(null, response); - }); + return Task.Run(() => + { + this.GoReceived(null, response); + }); } /// diff --git a/src/TouchSocket.Http/Extensions/HttpExtensions.cs b/src/TouchSocket.Http/Extensions/HttpExtensions.cs index 2b68dd030..1a7a76b15 100644 --- a/src/TouchSocket.Http/Extensions/HttpExtensions.cs +++ b/src/TouchSocket.Http/Extensions/HttpExtensions.cs @@ -148,7 +148,6 @@ namespace TouchSocket.Http public static T SetContentTypeByExtension(this T httpBase, string extension) where T : HttpBase { var type = HttpTools.GetContentTypeFromExtension(extension); - httpBase.Headers.Add(HttpHeaders.ContentType.GetDescription(), type); httpBase.ContentType = type; return httpBase; } @@ -378,7 +377,7 @@ namespace TouchSocket.Http /// /// /// - public static TResponse SetStatus(this TResponse response, string status = "200", string msg = "Success") where TResponse : HttpResponse + public static TResponse SetStatus(this TResponse response, int status = 200, string msg = "Success") where TResponse : HttpResponse { response.StatusCode = status; response.StatusMessage = msg; @@ -395,7 +394,7 @@ namespace TouchSocket.Http public static TResponse UrlNotFind(this TResponse response) where TResponse : HttpResponse { response.SetContent("

404 -RRQM Not Found

"); - response.StatusCode = "404"; + response.StatusCode = 404; response.ContentType = "text/html;charset=utf-8"; return response; } @@ -424,7 +423,7 @@ namespace TouchSocket.Http var contentDisposition = "attachment;" + "filename=" + System.Web.HttpUtility.UrlEncode(fileName ?? Path.GetFileName(filePath)); response.Headers.Add(HttpHeaders.ContentDisposition, contentDisposition); response.Headers.Add(HttpHeaders.AcceptRanges, "bytes"); - + if (response.CanWrite) { HttpRange httpRange; @@ -446,7 +445,7 @@ namespace TouchSocket.Http else { response.SetContentLength(httpRange.Length) - .SetStatus("206", "Partial Content"); + .SetStatus(206, "Partial Content"); response.Headers.Add(HttpHeaders.ContentRange, string.Format("bytes {0}-{1}/{2}", httpRange.Start, httpRange.Length + httpRange.Start - 1, reader.FileStorage.FileInfo.Length)); } } @@ -543,7 +542,7 @@ namespace TouchSocket.Http else { context.Response.SetContentLength(httpRange.Length) - .SetStatus("206", "Partial Content"); + .SetStatus(206, "Partial Content"); context.Response.Headers.Add(HttpHeaders.ContentRange, string.Format("bytes {0}-{1}/{2}", httpRange.Start, httpRange.Length + httpRange.Start - 1, reader.FileStorage.FileInfo.Length)); } } diff --git a/src/TouchSocket.Http/Extensions/HttpPluginsManagerExtension.cs b/src/TouchSocket.Http/Extensions/HttpPluginsManagerExtension.cs index 179577c66..d3cf01b65 100644 --- a/src/TouchSocket.Http/Extensions/HttpPluginsManagerExtension.cs +++ b/src/TouchSocket.Http/Extensions/HttpPluginsManagerExtension.cs @@ -27,6 +27,16 @@ namespace TouchSocket.Core public static DefaultHttpServicePlugin UseDefaultHttpServicePlugin(this IPluginsManager pluginsManager) { return pluginsManager.Add(); + } + + /// + /// 使用Http静态页面。 + /// + /// + /// + public static HttpStaticPagePlugin UseHttpStaticPage(this IPluginsManager pluginsManager) + { + return pluginsManager.Add(); } } } \ No newline at end of file diff --git a/src/TouchSocket.Http/Interface/IHttpHeader.cs b/src/TouchSocket.Http/Interface/IHttpHeader.cs index 8d015c498..ef9262546 100644 --- a/src/TouchSocket.Http/Interface/IHttpHeader.cs +++ b/src/TouchSocket.Http/Interface/IHttpHeader.cs @@ -1,17 +1,11 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace TouchSocket.Http { /// /// 表示http的headers /// - public interface IHttpHeader: IDictionary + public interface IHttpHeader : IDictionary { /// /// 获取Header @@ -32,13 +26,13 @@ namespace TouchSocket.Http /// /// /// - void Add(HttpHeaders key,string value); + void Add(HttpHeaders key, string value); /// /// 获取、添加Header /// /// /// - string this[HttpHeaders headers] { get;set; } + string this[HttpHeaders headers] { get; set; } } } diff --git a/src/TouchSocket.Http/Interface/IHttpParams.cs b/src/TouchSocket.Http/Interface/IHttpParams.cs new file mode 100644 index 000000000..290ce1395 --- /dev/null +++ b/src/TouchSocket.Http/Interface/IHttpParams.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace TouchSocket.Http +{ + /// + /// Http参数 + /// + public interface IHttpParams : IDictionary + { + /// + /// 获取参数 + /// + /// + /// + string Get(string key); + } +} diff --git a/src/TouchSocket.Http/Plugins/Interfaces/IHttpDeletePlugin.cs b/src/TouchSocket.Http/Plugins/Interfaces/IHttpDeletePlugin.cs index 7ec1ee060..13636f3ec 100644 --- a/src/TouchSocket.Http/Plugins/Interfaces/IHttpDeletePlugin.cs +++ b/src/TouchSocket.Http/Plugins/Interfaces/IHttpDeletePlugin.cs @@ -1,17 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Http { /// /// IHttpDeletePlugin /// - public interface IHttpDeletePlugin : IPlugin where TClient: IHttpSocketClient + public interface IHttpDeletePlugin : IPlugin where TClient : IHttpSocketClient { /// /// 在收到Delete时 @@ -25,8 +20,8 @@ namespace TouchSocket.Http /// /// IHttpDeletePlugin /// - public interface IHttpDeletePlugin: IHttpDeletePlugin - { - + public interface IHttpDeletePlugin : IHttpDeletePlugin + { + } } diff --git a/src/TouchSocket.Http/Plugins/Interfaces/IHttpGetPlugin.cs b/src/TouchSocket.Http/Plugins/Interfaces/IHttpGetPlugin.cs index f551cae36..d279f2660 100644 --- a/src/TouchSocket.Http/Plugins/Interfaces/IHttpGetPlugin.cs +++ b/src/TouchSocket.Http/Plugins/Interfaces/IHttpGetPlugin.cs @@ -1,17 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Http { /// /// IHttpGetPlugin /// - public interface IHttpGetPlugin:IPlugin where TClient : IHttpSocketClient + public interface IHttpGetPlugin : IPlugin where TClient : IHttpSocketClient { /// /// 在收到Get时 @@ -25,8 +20,8 @@ namespace TouchSocket.Http /// /// IHttpGetPlugin /// - public interface IHttpGetPlugin: IHttpGetPlugin - { - + public interface IHttpGetPlugin : IHttpGetPlugin + { + } } diff --git a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPlugin.cs b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPlugin.cs index bb598413e..5eb9a2b31 100644 --- a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPlugin.cs +++ b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPlugin.cs @@ -12,7 +12,6 @@ //------------------------------------------------------------------------------ using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Http { @@ -36,7 +35,7 @@ namespace TouchSocket.Http /// IHttpPlugin /// public interface IHttpPlugin : IHttpPlugin - { - + { + } } \ No newline at end of file diff --git a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPostPlugin.cs b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPostPlugin.cs index bd7d76be5..05f05a6a2 100644 --- a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPostPlugin.cs +++ b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPostPlugin.cs @@ -1,17 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Http { /// /// IHttpPostPlugin /// - public interface IHttpPostPlugin : IPlugin where TClient: IHttpSocketClient + public interface IHttpPostPlugin : IPlugin where TClient : IHttpSocketClient { /// /// 在收到Post时 @@ -25,8 +20,8 @@ namespace TouchSocket.Http /// /// IHttpPostPlugin /// - public interface IHttpPostPlugin: IHttpPostPlugin - { - + public interface IHttpPostPlugin : IHttpPostPlugin + { + } } diff --git a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPutPlugin.cs b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPutPlugin.cs index 628e2643d..8df65ada2 100644 --- a/src/TouchSocket.Http/Plugins/Interfaces/IHttpPutPlugin.cs +++ b/src/TouchSocket.Http/Plugins/Interfaces/IHttpPutPlugin.cs @@ -1,17 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Http { /// /// IHttpPutPlugin /// - public interface IHttpPutPlugin : IPlugin where TClient: IHttpSocketClient + public interface IHttpPutPlugin : IPlugin where TClient : IHttpSocketClient { /// /// 在收到Put时 @@ -25,8 +20,8 @@ namespace TouchSocket.Http /// /// IHttpPutPlugin /// - public interface IHttpPutPlugin: IHttpPutPlugin - { - + public interface IHttpPutPlugin : IHttpPutPlugin + { + } } diff --git a/src/TouchSocket.Http/TouchSocket.Http.csproj b/src/TouchSocket.Http/TouchSocket.Http.csproj index 70b84fabc..77416c1b7 100644 --- a/src/TouchSocket.Http/TouchSocket.Http.csproj +++ b/src/TouchSocket.Http/TouchSocket.Http.csproj @@ -1,55 +1,25 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 httpserver;httpclient;websocket - - 这是基于TouchSocket的,能够解析http1.1的服务器和客户端。它以插件的工作模式,能够像aspnetcore的中间件那样工作。同时,内部还包含了websocket,静态页面,大文件传输,多线程等功能。 + 这是基于TouchSocket的,能够解析http1.1的服务器和客户端。它以插件的工作模式,能够像aspnetcore的中间件那样工作。同时,内部还包含了websocket,静态页面,大文件传输,多线程等功能。 - 说明文档:http://rrqm_home.gitee.io/touchsocket - - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt +说明文档:http://rrqm_home.gitee.io/touchsocket TouchSocket.Http - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.Http + ..\..\Build\NugetPackages\TouchSocket.Http - - - True - - - - True - - - - - - - - + + + + True + Embedded + True + diff --git a/src/TouchSocket.Http/WebSockets/Common/WSTools.cs b/src/TouchSocket.Http/WebSockets/Common/WSTools.cs index db25ad31c..49ccf1dd7 100644 --- a/src/TouchSocket.Http/WebSockets/Common/WSTools.cs +++ b/src/TouchSocket.Http/WebSockets/Common/WSTools.cs @@ -183,7 +183,7 @@ namespace TouchSocket.Http.WebSockets return false; } - response.StatusCode = "101"; + response.StatusCode = 101; response.StatusMessage = "switching protocols"; response.Headers.Add(HttpHeaders.Connection, "upgrade"); response.Headers.Add(HttpHeaders.Upgrade, "websocket"); diff --git a/src/TouchSocket.Http/WebSockets/Components/WebSocketClient.cs b/src/TouchSocket.Http/WebSockets/Components/WebSocketClient.cs index 98b343e68..626c1dfcb 100644 --- a/src/TouchSocket.Http/WebSockets/Components/WebSocketClient.cs +++ b/src/TouchSocket.Http/WebSockets/Components/WebSocketClient.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; -using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; @@ -75,7 +74,7 @@ namespace TouchSocket.Http.WebSockets this.OnHandshaking(new HttpContextEventArgs(new HttpContext(request))); var response = this.Request(request, timeout: timeout, token: token); - if (!response.StatusCode.Trim().Equals("101")) + if (response.StatusCode != 101) { throw new WebSocketConnectException($"协议升级失败,信息:{response.StatusMessage},更多信息请捕获WebSocketConnectException异常,获得HttpContext得知。", new HttpContext(request, response)); } @@ -85,7 +84,7 @@ namespace TouchSocket.Http.WebSockets this.MainSocket.SafeDispose(); throw new WebSocketConnectException($"WS服务器返回的应答码不正确,更多信息请捕获WebSocketConnectException异常,获得HttpContext得知。", new HttpContext(request, response)); } - + this.SetAdapter(new WebSocketDataHandlingAdapter()); this.SetValue(WebSocketFeature.HandshakedProperty, true); response.Flag = true; @@ -110,6 +109,11 @@ namespace TouchSocket.Http.WebSockets #region 事件 + /// + /// 表示完成握手后。 + /// + public HttpContextEventHandler Handshaked { get; set; } + /// /// 表示在即将握手连接时。 /// @@ -118,7 +122,16 @@ namespace TouchSocket.Http.WebSockets /// /// 表示完成握手后。 /// - public HttpContextEventHandler Handshaked { get; set; } + /// + protected virtual void OnHandshaked(HttpContextEventArgs e) + { + this.Handshaked?.Invoke(this, e); + + if (this.PluginsManager.Raise(nameof(IWebSocketHandshakedPlugin.OnWebSocketHandshaked), this, e)) + { + return; + } + } /// /// 表示在即将握手连接时。 @@ -131,21 +144,7 @@ namespace TouchSocket.Http.WebSockets { return; } - if (this.PluginsManager.Raise(nameof(IWebsocketHandshakingPlugin.OnWebsocketHandshaking), this, e)) - { - return; - } - } - - /// - /// 表示完成握手后。 - /// - /// - protected virtual void OnHandshaked(HttpContextEventArgs e) - { - this.Handshaked?.Invoke(this, e); - - if (this.PluginsManager.Raise(nameof(IWebsocketHandshakedPlugin.OnWebsocketHandshaked), this, e)) + if (this.PluginsManager.Raise(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), this, e)) { return; } @@ -153,18 +152,6 @@ namespace TouchSocket.Http.WebSockets #endregion 事件 - /// - /// 当收到WS数据时。 - /// - /// - protected virtual void OnHandleWSDataFrame(WSDataFrame dataFrame) - { - if (this.PluginsManager.Enable) - { - this.PluginsManager.Raise(nameof(IWebsocketReceivedPlugin.OnWebsocketReceived), this, new WSDataFrameEventArgs(dataFrame)); - } - } - /// protected override bool HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo) { @@ -198,5 +185,17 @@ namespace TouchSocket.Http.WebSockets this.SetValue(WebSocketFeature.HandshakedProperty, false); base.OnDisconnected(e); } + + /// + /// 当收到WS数据时。 + /// + /// + protected virtual void OnHandleWSDataFrame(WSDataFrame dataFrame) + { + if (this.PluginsManager.Enable) + { + this.PluginsManager.Raise(nameof(IWebSocketReceivedPlugin.OnWebSocketReceived), this, new WSDataFrameEventArgs(dataFrame)); + } + } } } \ No newline at end of file diff --git a/src/TouchSocket.Http/WebSockets/Extensions/WSClientExtensions.cs b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketClientExtensions.cs similarity index 99% rename from src/TouchSocket.Http/WebSockets/Extensions/WSClientExtensions.cs rename to src/TouchSocket.Http/WebSockets/Extensions/WebSocketClientExtensions.cs index dc18f8aaa..80eb6c791 100644 --- a/src/TouchSocket.Http/WebSockets/Extensions/WSClientExtensions.cs +++ b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketClientExtensions.cs @@ -19,7 +19,7 @@ namespace TouchSocket.Http.WebSockets /// /// WSClientExtensions /// - public static class WSClientExtensions + public static class WebSocketClientExtensions { /// /// 发送Close报文。 @@ -50,7 +50,7 @@ namespace TouchSocket.Http.WebSockets } /// - /// 是否已经完成握手 + /// WebSocket是否已经完成握手 /// /// /// diff --git a/src/TouchSocket.Http/WebSockets/Extensions/WSDataFrameExtensions.cs b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketDataFrameExtensions.cs similarity index 98% rename from src/TouchSocket.Http/WebSockets/Extensions/WSDataFrameExtensions.cs rename to src/TouchSocket.Http/WebSockets/Extensions/WebSocketDataFrameExtensions.cs index 16b76f974..97382cf0a 100644 --- a/src/TouchSocket.Http/WebSockets/Extensions/WSDataFrameExtensions.cs +++ b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketDataFrameExtensions.cs @@ -18,7 +18,7 @@ namespace TouchSocket.Http.WebSockets /// /// WSDataFrame辅助扩展类 /// - public static class WSDataFrameExtensions + public static class WebSocketDataFrameExtensions { /// /// 追加二进制流 diff --git a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketExtension.cs b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketExtension.cs deleted file mode 100644 index d422334e9..000000000 --- a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketExtension.cs +++ /dev/null @@ -1,142 +0,0 @@ -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Runtime.CompilerServices; -//using System.Text; -//using System.Threading.Tasks; -//using TouchSocket.Core; - -//namespace TouchSocket.Http.WebSockets -//{ -// /// -// /// WebSocketExtension -// /// -// public static class WebSocketExtension -// { -// #region 同步发送 - -// /// -// /// 采用WebSocket协议,发送二进制流数据。 -// /// -// /// -// /// -// /// -// /// -// public static void Send(this IWebSocket webSocket,byte[] buffer, int offset, int length) -// { -// using (var frame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Binary }) -// { -// if (offset == 0) -// { -// frame.PayloadData = new ByteBlock(buffer, length); -// } -// else -// { -// frame.AppendBinary(buffer, offset, length); -// } -// webSocket.Send(frame); -// } -// } - -// /// -// /// 采用WebSocket协议,发送二进制流数据。 -// /// -// /// -// /// -// public static void Send(this IWebSocket webSocket,ByteBlock byteBlock) -// { -// using (var frame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Binary }) -// { -// frame.PayloadData = byteBlock; -// webSocket.Send(frame); -// } -// } - -// /// -// /// 采用WebSocket协议,发送二进制流数据。 -// /// -// /// -// /// -// public static void Send(this IWebSocket webSocket,byte[] buffer) -// { -// using (var frame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Binary }) -// { -// frame.PayloadData = new ByteBlock(buffer); -// webSocket.Send(frame); -// } -// } - -// /// -// /// 采用WebSocket协议,发送文本数据。 -// /// -// /// -// /// -// public static void Send(this IWebSocket webSocket,string text) -// { -// using (var dataFrame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Text }) -// { -// dataFrame.AppendText(text); -// webSocket.Send(dataFrame); -// } -// } - - - -// #endregion 同步发送 - -// #region 异步发送 - -// /// -// /// 采用WebSocket协议,发送二进制流数据。 -// /// -// /// -// /// -// /// -// /// -// public static Task SendAsync(this IWebSocket webSocket, byte[] buffer, int offset, int length) -// { -// using (var frame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Binary }) -// { -// if (offset == 0) -// { -// frame.PayloadData = new ByteBlock(buffer, length); -// } -// else -// { -// frame.AppendBinary(buffer, offset, length); -// } -// return webSocket.SendAsync(frame); -// } -// } - -// /// -// /// 采用WebSocket协议,发送二进制流数据。 -// /// -// /// -// /// -// public static Task SendAsync(this IWebSocket webSocket,byte[] buffer) -// { -// using (var frame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Binary }) -// { -// frame.PayloadData = new ByteBlock(buffer); -// return webSocket.SendAsync(frame); -// } -// } - -// /// -// /// 采用WebSocket协议,发送文本数据。 -// /// -// /// -// /// -// public static Task SendAsync(this IWebSocket webSocket,string text) -// { -// using (var dataFrame = new WSDataFrame() { FIN = true, Opcode = WSDataType.Text }) -// { -// dataFrame.AppendText(text); -// return webSocket.SendAsync(dataFrame); -// } -// } - -// #endregion 异步发送 -// } -//} diff --git a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketPluginsManagerExtension.cs b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketPluginsManagerExtension.cs index 0c5046a78..2da1653c0 100644 --- a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketPluginsManagerExtension.cs +++ b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketPluginsManagerExtension.cs @@ -33,10 +33,9 @@ namespace TouchSocket.Core /// 使用WebSocket心跳插件,客户端、服务器均有效。但是一般建议客户端使用即可。 /// /// 插件类型实例 - public static WebSocketHeartbeatPlugin UseWebSocketHeartbeat(this IPluginsManager pluginsManager) where TClient : IHttpClientBase + public static WebSocketHeartbeatPlugin UseWebSocketHeartbeat(this IPluginsManager pluginsManager) { - var heartbeatPlugin = new WebSocketHeartbeatPlugin(); - + var heartbeatPlugin = new WebSocketHeartbeatPlugin(); pluginsManager.Add(heartbeatPlugin); return heartbeatPlugin; } diff --git a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketServerExtensions.cs b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketServerExtensions.cs index 0a9e8c4cc..c0146034a 100644 --- a/src/TouchSocket.Http/WebSockets/Extensions/WebSocketServerExtensions.cs +++ b/src/TouchSocket.Http/WebSockets/Extensions/WebSocketServerExtensions.cs @@ -40,7 +40,7 @@ namespace TouchSocket.Http.WebSockets { IsPermitOperation = true }; - client.PluginsManager.Raise(nameof(IWebsocketHandshakingPlugin.OnWebsocketHandshaking), client, args); + client.PluginsManager.Raise(nameof(IWebSocketHandshakingPlugin.OnWebSocketHandshaking), client, args); if (args.Context.Response.Responsed) { return false; @@ -56,12 +56,12 @@ namespace TouchSocket.Http.WebSockets args.Context.Response.Build(byteBlock); client.DefaultSend(byteBlock); } - client.PluginsManager.Raise(nameof(IWebsocketHandshakedPlugin.OnWebsocketHandshaked), client, new HttpContextEventArgs(httpContext)); + client.PluginsManager.Raise(nameof(IWebSocketHandshakedPlugin.OnWebSocketHandshaked), client, new HttpContextEventArgs(httpContext)); return true; } else { - args.Context.Response.SetStatus("403", "Forbidden"); + args.Context.Response.SetStatus(403, "Forbidden"); using (var byteBlock = new ByteBlock()) { args.Context.Response.Build(byteBlock); diff --git a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketClosingPlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketClosingPlugin.cs index 11586db15..aee7e666d 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketClosingPlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketClosingPlugin.cs @@ -1,30 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Http.WebSockets { /// - /// IWebsocketClosingPlugin + /// IWebSocketClosingPlugin /// - public interface IWebsocketClosingPlugin:IPlugin where TClient: IHttpClientBase + public interface IWebSocketClosingPlugin : IPlugin where TClient : IHttpClientBase { /// /// 表示收到断开连接报文。如果对方直接断开连接,此方法则不会触发。 /// /// /// - Task OnWebsocketClosing(TClient client, MsgPermitEventArgs e); + Task OnWebSocketClosing(TClient client, MsgPermitEventArgs e); } /// - /// IWebsocketClosingPlugin + /// IWebSocketClosingPlugin /// - public interface IWebsocketClosingPlugin: IWebsocketClosingPlugin - { - + public interface IWebSocketClosingPlugin : IWebSocketClosingPlugin + { + } } diff --git a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakedPlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakedPlugin.cs index 2f1c94bb4..f1e1be5e5 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakedPlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakedPlugin.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Http.WebSockets { /// - /// IWebsocketHandshakedPlugin + /// IWebSocketHandshakedPlugin /// - public interface IWebsocketHandshakedPlugin : IPlugin where TClient : IHttpClientBase + public interface IWebSocketHandshakedPlugin : IPlugin where TClient : IHttpClientBase { /// /// 表示完成握手后。 @@ -18,14 +14,14 @@ namespace TouchSocket.Http.WebSockets /// /// /// - Task OnWebsocketHandshaked(TClient client, HttpContextEventArgs e); + Task OnWebSocketHandshaked(TClient client, HttpContextEventArgs e); } /// - /// IWebsocketHandshakedPlugin + /// IWebSocketHandshakedPlugin /// - public interface IWebsocketHandshakedPlugin : IWebsocketHandshakedPlugin - { - + public interface IWebSocketHandshakedPlugin : IWebSocketHandshakedPlugin + { + } } diff --git a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakingPlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakingPlugin.cs index 0dda2443f..7e2972e1b 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakingPlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketHandshakingPlugin.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Http.WebSockets { /// - /// IWebsocketHandshakingPlugin + /// IWebSocketHandshakingPlugin /// - public interface IWebsocketHandshakingPlugin : IPlugin where TClient : IHttpClientBase + public interface IWebSocketHandshakingPlugin : IPlugin where TClient : IHttpClientBase { /// /// 表示在即将握手连接时。 @@ -18,14 +14,14 @@ namespace TouchSocket.Http.WebSockets /// /// /// - Task OnWebsocketHandshaking(TClient client, HttpContextEventArgs e); + Task OnWebSocketHandshaking(TClient client, HttpContextEventArgs e); } /// - /// IWebsocketHandshakingPlugin + /// IWebSocketHandshakingPlugin /// - public interface IWebsocketHandshakingPlugin: IWebsocketHandshakingPlugin - { - + public interface IWebSocketHandshakingPlugin : IWebSocketHandshakingPlugin + { + } } diff --git a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketReceivedPlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketReceivedPlugin.cs index e056333f3..2c5fa1886 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketReceivedPlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/Interfaces/IWebsocketReceivedPlugin.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Http.WebSockets { /// - /// IWebsocketReceivedPlugin + /// IWebSocketReceivedPlugin /// - public interface IWebsocketReceivedPlugin : IPlugin where TClient : IHttpClientBase + public interface IWebSocketReceivedPlugin : IPlugin where TClient : IHttpClientBase { /// /// 当收到WS数据时。 @@ -18,15 +14,15 @@ namespace TouchSocket.Http.WebSockets /// /// /// - Task OnWebsocketReceived(TClient client, WSDataFrameEventArgs e); + Task OnWebSocketReceived(TClient client, WSDataFrameEventArgs e); } /// - /// IWebsocketReceivedPlugin + /// IWebSocketReceivedPlugin /// - public interface IWebsocketReceivedPlugin: IWebsocketReceivedPlugin - { - + public interface IWebSocketReceivedPlugin : IWebSocketReceivedPlugin + { + } } diff --git a/src/TouchSocket.Http/WebSockets/Plugins/WSCommandLinePlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketCommandLinePlugin.cs similarity index 94% rename from src/TouchSocket.Http/WebSockets/Plugins/WSCommandLinePlugin.cs rename to src/TouchSocket.Http/WebSockets/Plugins/WebSocketCommandLinePlugin.cs index 5524be21e..d761b2e0e 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/WSCommandLinePlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketCommandLinePlugin.cs @@ -23,7 +23,7 @@ namespace TouchSocket.Http.WebSockets /// /// WS命令行插件。 /// - public abstract class WSCommandLinePlugin : PluginBase, IWebsocketReceivedPlugin + public abstract class WebSocketCommandLinePlugin : PluginBase, IWebSocketReceivedPlugin { private readonly ILog m_logger; private readonly Dictionary m_pairs = new Dictionary(); @@ -33,7 +33,7 @@ namespace TouchSocket.Http.WebSockets /// /// /// - protected WSCommandLinePlugin(ILog logger) + protected WebSocketCommandLinePlugin(ILog logger) { this.m_logger = logger ?? throw new ArgumentNullException(nameof(logger)); this.Converter = new StringConverter(); @@ -58,14 +58,14 @@ namespace TouchSocket.Http.WebSockets /// 当有执行异常时,不返回异常。 /// /// - public WSCommandLinePlugin NoReturnException() + public WebSocketCommandLinePlugin NoReturnException() { this.ReturnException = false; return this; } /// - public async Task OnWebsocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) + public async Task OnWebSocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) { if (e.DataFrame.Opcode == WSDataType.Text) { @@ -130,7 +130,7 @@ namespace TouchSocket.Http.WebSockets } else { - await e.InvokeNext(); + await e.InvokeNext(); } } } diff --git a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeature.cs b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeature.cs index 849a69cd4..d7e082bfb 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeature.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeature.cs @@ -157,7 +157,7 @@ namespace TouchSocket.Http.WebSockets if (this.AutoClose && e.DataFrame.Opcode == WSDataType.Close) { var msg = e.DataFrame.PayloadData?.ToString(); - this.m_pluginsManager.Raise(nameof(IWebsocketClosingPlugin.OnWebsocketClosing), client, new MsgPermitEventArgs() { Message = msg }); + this.m_pluginsManager.Raise(nameof(IWebSocketClosingPlugin.OnWebSocketClosing), client, new MsgPermitEventArgs() { Message = msg }); client.Close(msg); return; } @@ -167,7 +167,7 @@ namespace TouchSocket.Http.WebSockets return; } - this.m_pluginsManager.Raise(nameof(IWebsocketReceivedPlugin.OnWebsocketReceived), client, e); + this.m_pluginsManager.Raise(nameof(IWebSocketReceivedPlugin.OnWebSocketReceived), client, e); } private bool ThisVerifyConnection(IHttpSocketClient client, HttpContext context) diff --git a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketHeartbeatPlugin.cs b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketHeartbeatPlugin.cs index 5759721b7..40a9cdbd6 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketHeartbeatPlugin.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketHeartbeatPlugin.cs @@ -10,9 +10,9 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System; using System.Threading.Tasks; using TouchSocket.Core; +using TouchSocket.Sockets; namespace TouchSocket.Http.WebSockets { @@ -20,29 +20,14 @@ namespace TouchSocket.Http.WebSockets /// 初始化一个适用于WebSocket的心跳插件 /// [PluginOption(Singleton = true, NotRegister = true)] - public class WebSocketHeartbeatPlugin : PluginBase, IWebsocketHandshakedPlugin where TClient : IHttpClientBase + public class WebSocketHeartbeatPlugin : HeartbeatPlugin, IWebSocketHandshakedPlugin { - /// - /// 心跳频率 - /// - public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(5); - - - /// - /// 设置心跳间隔,默认5秒。 - /// - /// - public WebSocketHeartbeatPlugin SetTick(TimeSpan timeSpan) - { - this.Tick = timeSpan; - return this; - } - /// - public Task OnWebsocketHandshaked(TClient client, HttpContextEventArgs e) + Task IWebSocketHandshakedPlugin.OnWebSocketHandshaked(IHttpClientBase client, HttpContextEventArgs e) { - Task.Run(async() => + Task.Run(async () => { + var failedCount = 0; while (true) { await Task.Delay(this.Tick); @@ -50,13 +35,19 @@ namespace TouchSocket.Http.WebSockets { return; } - if (client is IHttpClient httpClient) + + try { - httpClient.PingWS(); + client.PingWS(); + failedCount = 0; } - else if (client is IHttpSocketClient httpSocketClient) + catch { - httpSocketClient.PingWS(); + failedCount++; + } + if (failedCount > this.MaxFailCount) + { + client.CloseWithWS("自动心跳失败次数达到最大,已断开连接。"); } } }); diff --git a/src/TouchSocket.JsonRpc/Common/HttpJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Common/HttpJsonRpcCallContext.cs new file mode 100644 index 000000000..abaad6571 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Common/HttpJsonRpcCallContext.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Http; +using TouchSocket.WebApi; + +namespace TouchSocket.JsonRpc +{ + /// + /// HttpJsonRpcCallContext + /// + class HttpJsonRpcCallContext : JsonRpcCallContextBase, IHttpCallContext + { + /// + /// HttpJsonRpcCallContext + /// + /// + /// + /// + public HttpJsonRpcCallContext(object caller, string jsonString, HttpContext context) : base(caller, jsonString) + { + this.HttpContext = context; + } + + /// + public HttpContext HttpContext { get; } + } +} diff --git a/src/TouchSocket.JsonRpc/Common/JsonResponseContext.cs b/src/TouchSocket.JsonRpc/Common/JsonResponseContext.cs index 41f62a326..5d24db40e 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonResponseContext.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonResponseContext.cs @@ -11,6 +11,8 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using Newtonsoft.Json; + namespace TouchSocket.JsonRpc { /// @@ -21,40 +23,25 @@ namespace TouchSocket.JsonRpc /// /// jsonrpc /// - public string jsonrpc { get; set; } + [JsonProperty("jsonrpc")] + public string Jsonrpc { get; set; } /// /// result /// - public object result { get; set; } + [JsonProperty("result")] + public object Result { get; set; } /// /// error /// - public error error { get; set; } + [JsonProperty("error")] + public JsonRpcError Error { get; set; } /// /// id /// - public string id { get; set; } - } - - /// - /// 错误 - /// -#pragma warning disable IdE1006 // 命名样式 - - public class error -#pragma warning restore IdE1006 // 命名样式 - { - /// - /// code - /// - public int code { get; set; } - - /// - /// message - /// - public string message { get; set; } + [JsonProperty("id")] + public string Id { get; set; } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcCallContextBase.cs similarity index 75% rename from src/TouchSocket.JsonRpc/Common/JsonRpcCallContext.cs rename to src/TouchSocket.JsonRpc/Common/JsonRpcCallContextBase.cs index c3c7b9978..70dae37d1 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcCallContext.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcCallContextBase.cs @@ -12,7 +12,6 @@ //------------------------------------------------------------------------------ using System.Threading; -using TouchSocket.Http; using TouchSocket.Rpc; namespace TouchSocket.JsonRpc @@ -20,25 +19,36 @@ namespace TouchSocket.JsonRpc /// /// JsonRpc调用上下文 /// - internal class JsonRpcCallContext : IJsonRpcCallContext + public abstract class JsonRpcCallContextBase : IJsonRpcCallContext { private CancellationTokenSource m_tokenSource; /// - /// Json字符串 + /// JsonRpc调用上下文 /// - public string JsonString { get; internal set; } + /// + /// + public JsonRpcCallContextBase(object caller, string jsonString) + { + this.Caller = caller; + this.JsonString = jsonString; + } /// /// /// - public object Caller { get; internal set; } + public object Caller { get; } /// /// JsonRpc上下文 /// public JsonRpcContext JsonRpcContext { get; internal set; } + /// + /// Json字符串 + /// + public string JsonString { get; } + /// /// /// @@ -51,22 +61,9 @@ namespace TouchSocket.JsonRpc { get { - if (this.m_tokenSource == null) - { - this.m_tokenSource = new CancellationTokenSource(); - } + this.m_tokenSource ??= new CancellationTokenSource(); return this.m_tokenSource; } } - - /// - /// - /// - public HttpContext HttpContext { get; internal set; } - - /// - /// - /// - public JRPT JRPT { get; internal set; } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcContext.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcContext.cs index a6fca531a..fe70be977 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcContext.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcContext.cs @@ -11,6 +11,8 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using Newtonsoft.Json; + namespace TouchSocket.JsonRpc { /// @@ -21,11 +23,13 @@ namespace TouchSocket.JsonRpc /// /// parameters /// - public object[] parameters; + [JsonProperty("parameters")] + public object[] Parameters { get; set; } /// /// needResponse /// - public bool needResponse; + [JsonProperty("needResponse")] + public bool NeedResponse { get; set; } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcError.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcError.cs new file mode 100644 index 000000000..231b36556 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcError.cs @@ -0,0 +1,27 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + /// + /// JsonRpcError + /// + public class JsonRpcError + { + /// + /// code + /// + [JsonProperty("code")] + public int Code { get; set; } + + /// + /// message + /// + [JsonProperty("message")] + public string Message { get; set; } + } +} diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcRequest.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcRequest.cs index 10331563d..6d4bb4686 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcRequest.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcRequest.cs @@ -11,6 +11,8 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using Newtonsoft.Json; + namespace TouchSocket.JsonRpc { /// @@ -21,21 +23,25 @@ namespace TouchSocket.JsonRpc /// /// jsonrpc /// - public string jsonrpc = "2.0"; + [JsonProperty("jsonrpc")] + public string Jsonrpc = "2.0"; /// /// method /// - public string method; + [JsonProperty("method")] + public string Method; /// /// @params /// - public object @params; + [JsonProperty("params")] + public object Params; /// /// id /// - public string id; + [JsonProperty("id")] + public string Id; } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcResponse.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcResponse.cs index d0197190d..de78a6ec0 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcResponse.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcResponse.cs @@ -47,7 +47,7 @@ namespace TouchSocket.JsonRpc /// /// error /// - public error error; + public JsonRpcError error; /// /// id diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcUtility.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcUtility.cs index aa567f71a..b2389b011 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcUtility.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcUtility.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Sockets; +using TouchSocket.Sockets; namespace TouchSocket.JsonRpc { @@ -13,9 +8,9 @@ namespace TouchSocket.JsonRpc public static class JsonRpcUtility { /// - /// JsonRpc + /// TcpJsonRpc /// - public static Protocol JsonRpc { get; private set; } = new Protocol("JsonRpc"); + public static Protocol TcpJsonRpc { get; private set; } = new Protocol("TcpJsonRpc"); } } diff --git a/src/TouchSocket.JsonRpc/Common/JsonRpcWaitResult.cs b/src/TouchSocket.JsonRpc/Common/JsonRpcWaitResult.cs index 50833bc3f..e2c0c9ffa 100644 --- a/src/TouchSocket.JsonRpc/Common/JsonRpcWaitResult.cs +++ b/src/TouchSocket.JsonRpc/Common/JsonRpcWaitResult.cs @@ -16,8 +16,8 @@ namespace TouchSocket.JsonRpc { internal class JsonRpcWaitResult : WaitResult { - internal object Return; + public object Return; - internal error error; + public JsonRpcError Error; } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Common/TcpJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Common/TcpJsonRpcCallContext.cs new file mode 100644 index 000000000..fd5b76c7c --- /dev/null +++ b/src/TouchSocket.JsonRpc/Common/TcpJsonRpcCallContext.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + /// + /// TcpJsonRpcCallContext + /// + internal class TcpJsonRpcCallContext : JsonRpcCallContextBase, ITcpJsonRpcCallContext + { + /// + /// TcpJsonRpcCallContext + /// + /// + /// + public TcpJsonRpcCallContext(object caller, string jsonString) : base(caller, jsonString) + { + } + } +} diff --git a/src/TouchSocket.JsonRpc/Common/WebSocketJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Common/WebSocketJsonRpcCallContext.cs new file mode 100644 index 000000000..74ddf0dc0 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Common/WebSocketJsonRpcCallContext.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + internal class WebSocketJsonRpcCallContext : JsonRpcCallContextBase + { + public WebSocketJsonRpcCallContext(object caller, string jsonString) : base(caller, jsonString) + { + } + } +} diff --git a/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClient.cs new file mode 100644 index 000000000..e07f00fd9 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClient.cs @@ -0,0 +1,345 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Http; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// 基于Http协议的JsonRpc客户端 + /// + public class HttpJsonRpcClient:HttpClientBase, IHttpJsonRpcClient + { + private readonly WaitHandlePool m_waitHandle=new WaitHandlePool(); + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) + { + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + var request = new HttpRequest(); + request.Method = HttpMethod.Post; + request.SetUrl(this.RemoteIPHost.PathAndQuery); + request.FromJson(jsonRpcRequest.ToJson()); + request.Build(byteBlock); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitSend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + this.Send(byteBlock); + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) + { + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + var request = new HttpRequest(); + request.Method = HttpMethod.Post; + request.SetUrl(this.RemoteIPHost.PathAndQuery); + request.FromJson(jsonRpcRequest.ToJson()); + request.Build(byteBlock); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitSend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + this.Send(byteBlock); + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) + { + this.Invoke(method, invokeOption, ref parameters, null); + } + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + return this.Invoke(returnType, method, invokeOption, ref parameters, null); + } + + /// + public async Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) + { + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + var request = new HttpRequest(); + request.Method = HttpMethod.Post; + request.SetUrl(this.RemoteIPHost.PathAndQuery); + request.FromJson(jsonRpcRequest.ToJson()); + request.Build(byteBlock); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitSend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + this.Send(byteBlock); + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + } + + /// + public async Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) + { + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + var request = new HttpRequest(); + request.Method = HttpMethod.Post; + request.SetUrl(this.RemoteIPHost.PathAndQuery); + request.FromJson(jsonRpcRequest.ToJson()); + request.Build(byteBlock); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitSend: + { + this.Send(byteBlock); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + this.Send(byteBlock); + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + } + + + /// + protected override bool HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo) + { + var httpResponse = (HttpResponse)requestInfo; + var jsonString = httpResponse.GetBody(); + + if (string.IsNullOrEmpty(jsonString)) + { + return base.HandleReceivedData(byteBlock, requestInfo); + } + + try + { + if (jsonString.Contains("error") || jsonString.Contains("result")) + { + var responseContext = jsonString.FromJson(); + if (responseContext != null && !responseContext.Id.IsNullOrEmpty()) + { + var waitContext = new JsonRpcWaitResult + { + Status = 1, + Sign = long.Parse(responseContext.Id), + Error = responseContext.Error, + Return = responseContext.Result + }; + this.m_waitHandle.SetRun(waitContext); + } + } + } + catch + { + } + return base.HandleReceivedData(byteBlock, requestInfo); + } + } +} diff --git a/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClientSlim.cs b/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClientSlim.cs new file mode 100644 index 000000000..8dc545121 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Components/HttpJsonRpcClientSlim.cs @@ -0,0 +1,322 @@ +//#if !NET45 +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Net.Http; +//using System.Text; +//using System.Threading.Tasks; +//using TouchSocket.Core; +//using TouchSocket.Rpc; + +//namespace TouchSocket.JsonRpc +//{ +// /// +// /// 基于通讯模型的JsonRpc客户端 +// /// +// public class HttpJsonRpcClientSlim:Http.HttpClientSlim, IHttpJsonRpcClientSlim +// { +// /// +// /// 基于通讯模型的JsonRpc客户端 +// /// +// /// +// public HttpJsonRpcClientSlim(System.Net.Http.HttpClient httpClient = default):base(httpClient) +// { + +// } + +// private readonly WaitHandlePool m_waitHandle = new WaitHandlePool(); + +// /// +// public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) +// { +// var context = new JsonRpcWaitResult(); +// var waitData = this.m_waitHandle.GetWaitData(context); + +// using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) +// { +// if (invokeOption == default) +// { +// invokeOption = InvokeOption.WaitInvoke; +// } + +// parameters ??= new object[0]; +// var jsonRpcRequest = new JsonRpcRequest +// { +// Method = method, +// Params = parameters, +// Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null +// }; +// var request = new HttpRequestMessage(); +// request.Method = HttpMethod.Post; +// request.RequestUri=(this.RemoteIPHost.PathAndQuery); +// request.FromJson(jsonRpcRequest.ToJson()); +// request.Build(byteBlock); +// switch (invokeOption.FeedbackType) +// { +// case FeedbackType.OnlySend: +// { +// this.HttpClient.po(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return default; +// } +// case FeedbackType.WaitSend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return default; +// } +// case FeedbackType.WaitInvoke: +// { +// this.Send(byteBlock); +// waitData.Wait(invokeOption.Timeout); +// var resultContext = (JsonRpcWaitResult)waitData.WaitResult; +// this.m_waitHandle.Destroy(waitData); + +// if (resultContext.Status == 0) +// { +// throw new TimeoutException("等待结果超时"); +// } +// if (resultContext.Error != null) +// { +// throw new RpcException(resultContext.Error.Message); +// } + +// if (resultContext.Return == null) +// { +// return default; +// } +// else +// { +// if (returnType.IsPrimitive || returnType == typeof(string)) +// { +// return resultContext.Return.ToString().ParseToType(returnType); +// } +// else +// { +// return resultContext.Return.ToJson().FromJson(returnType); +// } +// } +// } +// default: +// return default; +// } +// } +// } + +// /// +// public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) +// { +// var context = new JsonRpcWaitResult(); +// var waitData = this.m_waitHandle.GetWaitData(context); + +// using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) +// { +// if (invokeOption == default) +// { +// invokeOption = InvokeOption.WaitInvoke; +// } +// parameters ??= new object[0]; +// var jsonRpcRequest = new JsonRpcRequest() +// { +// Method = method, +// Params = parameters +// }; + +// jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; +// var request = new HttpRequest(); +// request.Method = HttpMethod.Post; +// request.SetUrl(this.RemoteIPHost.PathAndQuery); +// request.FromJson(jsonRpcRequest.ToJson()); +// request.Build(byteBlock); +// switch (invokeOption.FeedbackType) +// { +// case FeedbackType.OnlySend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return; +// } +// case FeedbackType.WaitSend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return; +// } +// case FeedbackType.WaitInvoke: +// { +// this.Send(byteBlock); +// waitData.Wait(invokeOption.Timeout); +// var resultContext = (JsonRpcWaitResult)waitData.WaitResult; +// this.m_waitHandle.Destroy(waitData); + +// if (resultContext.Status == 0) +// { +// throw new TimeoutException("等待结果超时"); +// } +// if (resultContext.Error != null) +// { +// throw new RpcException(resultContext.Error.Message); +// } +// break; +// } +// default: +// return; +// } +// } +// } + +// /// +// public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) +// { +// this.Invoke(method, invokeOption, ref parameters, null); +// } + +// /// +// public object Invoke(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) +// { +// return this.Invoke(returnType, method, invokeOption, ref parameters, null); +// } + +// /// +// public async Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) +// { +// var context = new JsonRpcWaitResult(); +// var waitData = this.m_waitHandle.GetWaitDataAsync(context); + +// using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) +// { +// if (invokeOption == default) +// { +// invokeOption = InvokeOption.WaitInvoke; +// } +// parameters ??= new object[0]; +// var jsonRpcRequest = new JsonRpcRequest() +// { +// Method = method, +// Params = parameters +// }; + +// jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; +// var request = new HttpRequest(); +// request.Method = HttpMethod.Post; +// request.SetUrl(this.RemoteIPHost.PathAndQuery); +// request.FromJson(jsonRpcRequest.ToJson()); +// request.Build(byteBlock); +// switch (invokeOption.FeedbackType) +// { +// case FeedbackType.OnlySend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return; +// } +// case FeedbackType.WaitSend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return; +// } +// case FeedbackType.WaitInvoke: +// { +// this.Send(byteBlock); +// await waitData.WaitAsync(invokeOption.Timeout); +// var resultContext = (JsonRpcWaitResult)waitData.WaitResult; +// this.m_waitHandle.Destroy(waitData); + +// if (resultContext.Status == 0) +// { +// throw new TimeoutException("等待结果超时"); +// } +// if (resultContext.Error != null) +// { +// throw new RpcException(resultContext.Error.Message); +// } +// break; +// } +// default: +// return; +// } +// } +// } + +// /// +// public async Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) +// { +// var context = new JsonRpcWaitResult(); +// var waitData = this.m_waitHandle.GetWaitDataAsync(context); + +// using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) +// { +// if (invokeOption == default) +// { +// invokeOption = InvokeOption.WaitInvoke; +// } +// parameters ??= new object[0]; +// var jsonRpcRequest = new JsonRpcRequest +// { +// Method = method, +// Params = parameters, +// Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null +// }; +// var request = new HttpRequest(); +// request.Method = HttpMethod.Post; +// request.SetUrl(this.RemoteIPHost.PathAndQuery); +// request.FromJson(jsonRpcRequest.ToJson()); +// request.Build(byteBlock); +// switch (invokeOption.FeedbackType) +// { +// case FeedbackType.OnlySend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return default; +// } +// case FeedbackType.WaitSend: +// { +// this.Send(byteBlock); +// this.m_waitHandle.Destroy(waitData); +// return default; +// } +// case FeedbackType.WaitInvoke: +// { +// this.Send(byteBlock); +// await waitData.WaitAsync(invokeOption.Timeout); +// var resultContext = (JsonRpcWaitResult)waitData.WaitResult; +// this.m_waitHandle.Destroy(waitData); + +// if (resultContext.Status == 0) +// { +// throw new TimeoutException("等待结果超时"); +// } +// if (resultContext.Error != null) +// { +// throw new RpcException(resultContext.Error.Message); +// } + +// if (resultContext.Return == null) +// { +// return default; +// } +// else +// { +// if (returnType.IsPrimitive || returnType == typeof(string)) +// { +// return resultContext.Return.ToString().ParseToType(returnType); +// } +// else +// { +// return resultContext.Return.ToJson().FromJson(returnType); +// } +// } +// } +// default: +// return default; +// } +// } +// } + + +// } +//} + +//#endif diff --git a/src/TouchSocket.JsonRpc/Components/JsonRpcClient.cs b/src/TouchSocket.JsonRpc/Components/JsonRpcClient.cs deleted file mode 100644 index b8393642f..000000000 --- a/src/TouchSocket.JsonRpc/Components/JsonRpcClient.cs +++ /dev/null @@ -1,712 +0,0 @@ -//------------------------------------------------------------------------------ -// 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 -// 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 -// CSDN博客:https://blog.csdn.net/qq_40374647 -// 哔哩哔哩视频:https://space.bilibili.com/94253567 -// Gitee源代码仓库:https://gitee.com/RRQM_Home -// Github源代码仓库:https://github.com/RRQM -// API首页:http://rrqm_home.gitee.io/touchsocket/ -// 交流QQ群:234762506 -// 感谢您的下载和使用 -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ - -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Sockets; -using System.Threading.Tasks; -using TouchSocket.Core; -using TouchSocket.Http; -using TouchSocket.Http.WebSockets; -using TouchSocket.Rpc; -using TouchSocket.Sockets; - -namespace TouchSocket.JsonRpc -{ - /// - /// JsonRpc客户端 - /// - public class JsonRpcClient : DisposableObject, ITcpClient, IJsonRpcClient - { - private readonly WaitHandlePool m_waitHandle; - - /// - /// JsonRpc客户端 - /// - public JsonRpcClient() - { - this.m_waitHandle = new WaitHandlePool(); - this.Protocol = JsonRpcUtility.JsonRpc; - } - - /// - public int BufferLength => this.Client.BufferLength; - - /// - public bool CanSend => this.Client.CanSend; - - /// - public bool CanSetDataHandlingAdapter => this.Client.CanSetDataHandlingAdapter; - - /// - /// 内部客户端 - /// - public ITcpClient Client { get; private set; } - - /// - public TouchSocketConfig Config => this.Client.Config; - - /// - public ConnectedEventHandler Connected { get => this.Client.Connected; set => this.Client.Connected = value; } - - /// - public ConnectingEventHandler Connecting { get => this.Client.Connecting; set => this.Client.Connecting = value; } - - /// - public IContainer Container => ((IClient)this.Client).Container; - - /// - public TcpDataHandlingAdapter DataHandlingAdapter => this.Client.DataHandlingAdapter; - - /// - public DisconnectEventHandler Disconnected { get => this.Client.Disconnected; set => this.Client.Disconnected = value; } - - /// - public DisconnectEventHandler Disconnecting { get => this.Client.Disconnecting; set => this.Client.Disconnecting = value; } - - /// - public string IP => this.Client.IP; - - /// - public bool IsClient => this.Client.IsClient; - - /// - /// 协议类型 - /// - public JRPT JRPT { get; private set; } - - /// - public DateTime LastReceivedTime => this.Client.LastReceivedTime; - - /// - public DateTime LastSendTime => this.Client.LastSendTime; - - /// - public ILog Logger => this.Client.Logger; - - /// - public Socket MainSocket => this.Client.MainSocket; - - /// - public Func OnHandleRawBuffer { get => this.Client.OnHandleRawBuffer; set => this.Client.OnHandleRawBuffer = value; } - - /// - public Func OnHandleReceivedData { get => this.Client.OnHandleReceivedData; set => this.Client.OnHandleReceivedData = value; } - - /// - public bool Online => this.Client.Online; - - /// - public IPluginsManager PluginsManager => this.Client.PluginsManager; - - /// - public int Port => this.Client.Port; - - /// - public Protocol Protocol { get ; set; } - - /// - public ReceiveType ReceiveType => this.Client.ReceiveType; - - /// - public IPHost RemoteIPHost => this.Client.RemoteIPHost; - - - /// - public bool UseSsl => this.Client.UseSsl; - - /// - public void Close(string msg) - { - this.Client.Close(msg); - } - - /// - public ITcpClient Connect(int timeout = 5000) - { - this.Client.OnHandleReceivedData = this.HandleReceivedData; - this.Client.Connect(timeout); - return this; - } - - /// - public Task ConnectAsync(int timeout = 5000) - { - return Task.Run(() => - { - return this.Connect(timeout); - }); - } - - /// - public void DefaultSend(byte[] buffer, int offset, int length) - { - this.Client.DefaultSend(buffer, offset, length); - } - - /// - public Task DefaultSendAsync(byte[] buffer, int offset, int length) - { - return this.Client.DefaultSendAsync(buffer, offset, length); - } - - /// - public Stream GetStream() - { - return this.Client.GetStream(); - } - - /// - public TValue GetValue(IDependencyProperty dp) - { - return this.Client.GetValue(dp); - } - - /// - public bool HasValue(IDependencyProperty dp) - { - return this.Client.HasValue(dp); - } - - /// - public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) - { - var context = new JsonRpcWaitResult(); - var waitData = this.m_waitHandle.GetWaitData(context); - - using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) - { - if (invokeOption == default) - { - invokeOption = InvokeOption.WaitInvoke; - } - - parameters ??= new object[0]; - var jsonRpcRequest = new JsonRpcRequest - { - method = method, - @params = parameters, - id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null - }; - switch (this.JRPT) - { - case JRPT.Tcp: - { - byteBlock.Write(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); - break; - } - case JRPT.Http: - { - var request = new HttpRequest(); - request.Method = HttpMethod.Post; - request.SetUrl(this.RemoteIPHost.PathAndQuery); - request.FromJson(jsonRpcRequest.ToJson()); - request.Build(byteBlock); - break; - } - case JRPT.Websocket: - { - ((WebSocketClient)this.Client).SendWithWS(jsonRpcRequest.ToJson()); - break; - } - } - switch (invokeOption.FeedbackType) - { - case FeedbackType.OnlySend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return default; - } - case FeedbackType.WaitSend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return default; - } - case FeedbackType.WaitInvoke: - { - this.Send(byteBlock); - waitData.Wait(invokeOption.Timeout); - var resultContext = (JsonRpcWaitResult)waitData.WaitResult; - this.m_waitHandle.Destroy(waitData); - - if (resultContext.Status == 0) - { - throw new TimeoutException("等待结果超时"); - } - if (resultContext.error != null) - { - throw new RpcException(resultContext.error.message); - } - - if (resultContext.Return == null) - { - return default; - } - else - { - if (returnType.IsPrimitive || returnType == typeof(string)) - { - return resultContext.Return.ToString().ParseToType(returnType); - } - else - { - return resultContext.Return.ToJson().FromJson(returnType); - } - } - } - default: - return default; - } - } - } - - /// - public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) - { - var context = new JsonRpcWaitResult(); - var waitData = this.m_waitHandle.GetWaitData(context); - - using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) - { - if (invokeOption == default) - { - invokeOption = InvokeOption.WaitInvoke; - } - parameters ??= new object[0]; - var jsonRpcRequest = new JsonRpcRequest() - { - method = method, - @params = parameters - }; - - jsonRpcRequest.id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; - switch (this.JRPT) - { - case JRPT.Tcp: - { - byteBlock.Write(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); - break; - } - case JRPT.Websocket: - { - ((WebSocketClient)this.Client).SendWithWS(jsonRpcRequest.ToJson()); - break; - } - case JRPT.Http: - { - var request = new HttpRequest(); - request.Method = HttpMethod.Post; - request.SetUrl(this.RemoteIPHost.PathAndQuery); - request.FromJson(jsonRpcRequest.ToJson()); - request.Build(byteBlock); - } - break; - } - switch (invokeOption.FeedbackType) - { - case FeedbackType.OnlySend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return; - } - case FeedbackType.WaitSend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return; - } - case FeedbackType.WaitInvoke: - { - this.Send(byteBlock); - waitData.Wait(invokeOption.Timeout); - var resultContext = (JsonRpcWaitResult)waitData.WaitResult; - this.m_waitHandle.Destroy(waitData); - - if (resultContext.Status == 0) - { - throw new TimeoutException("等待结果超时"); - } - if (resultContext.error != null) - { - throw new RpcException(resultContext.error.message); - } - break; - } - default: - return; - } - } - } - - /// - public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) - { - this.Invoke(method, invokeOption, ref parameters, null); - } - - /// - public object Invoke(Type returnType,string method, IInvokeOption invokeOption, params object[] parameters) - { - return this.Invoke(returnType,method, invokeOption, ref parameters, null); - } - - /// - public async Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) - { - var context = new JsonRpcWaitResult(); - var waitData = this.m_waitHandle.GetWaitDataAsync(context); - - using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) - { - if (invokeOption == default) - { - invokeOption = InvokeOption.WaitInvoke; - } - parameters ??= new object[0]; - var jsonRpcRequest = new JsonRpcRequest() - { - method = method, - @params = parameters - }; - - jsonRpcRequest.id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; - switch (this.JRPT) - { - case JRPT.Tcp: - { - byteBlock.Write(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); - break; - } - case JRPT.Websocket: - { - ((WebSocketClient)this.Client).SendWithWS(jsonRpcRequest.ToJson()); - break; - } - case JRPT.Http: - { - var request = new HttpRequest(); - request.Method = HttpMethod.Post; - request.SetUrl(this.RemoteIPHost.PathAndQuery); - request.FromJson(jsonRpcRequest.ToJson()); - request.Build(byteBlock); - } - break; - } - switch (invokeOption.FeedbackType) - { - case FeedbackType.OnlySend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return; - } - case FeedbackType.WaitSend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return; - } - case FeedbackType.WaitInvoke: - { - this.Send(byteBlock); - await waitData.WaitAsync(invokeOption.Timeout); - var resultContext = (JsonRpcWaitResult)waitData.WaitResult; - this.m_waitHandle.Destroy(waitData); - - if (resultContext.Status == 0) - { - throw new TimeoutException("等待结果超时"); - } - if (resultContext.error != null) - { - throw new RpcException(resultContext.error.message); - } - break; - } - default: - return; - } - } - } - - /// - public async Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) - { - var context = new JsonRpcWaitResult(); - var waitData = this.m_waitHandle.GetWaitDataAsync(context); - - using (var byteBlock = BytePool.Default.GetByteBlock(this.BufferLength)) - { - if (invokeOption == default) - { - invokeOption = InvokeOption.WaitInvoke; - } - parameters ??= new object[0]; - var jsonRpcRequest = new JsonRpcRequest - { - method = method, - @params = parameters, - id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null - }; - switch (this.JRPT) - { - case JRPT.Tcp: - { - byteBlock.Write(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); - break; - } - case JRPT.Http: - { - var request = new HttpRequest(); - request.Method = HttpMethod.Post; - request.SetUrl(this.RemoteIPHost.PathAndQuery); - request.FromJson(jsonRpcRequest.ToJson()); - request.Build(byteBlock); - break; - } - case JRPT.Websocket: - { - ((WebSocketClient)this.Client).SendWithWS(jsonRpcRequest.ToJson()); - break; - } - } - switch (invokeOption.FeedbackType) - { - case FeedbackType.OnlySend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return default; - } - case FeedbackType.WaitSend: - { - this.Send(byteBlock); - this.m_waitHandle.Destroy(waitData); - return default; - } - case FeedbackType.WaitInvoke: - { - this.Send(byteBlock); - await waitData.WaitAsync(invokeOption.Timeout); - var resultContext = (JsonRpcWaitResult)waitData.WaitResult; - this.m_waitHandle.Destroy(waitData); - - if (resultContext.Status == 0) - { - throw new TimeoutException("等待结果超时"); - } - if (resultContext.error != null) - { - throw new RpcException(resultContext.error.message); - } - - if (resultContext.Return == null) - { - return default; - } - else - { - if (returnType.IsPrimitive || returnType == typeof(string)) - { - return resultContext.Return.ToString().ParseToType(returnType); - } - else - { - return resultContext.Return.ToJson().FromJson(returnType); - } - } - } - default: - return default; - } - } - } - - /// - public DependencyObject RemoveValue(IDependencyProperty dp) - { - return this.Client.RemoveValue(dp); - } - - /// - public void Send(byte[] buffer, int offset, int length) - { - this.Client.Send(buffer, offset, length); - } - - /// - public void Send(IRequestInfo requestInfo) - { - this.Client.Send(requestInfo); - } - - /// - public void Send(IList> transferBytes) - { - this.Client.Send(transferBytes); - } - - /// - public Task SendAsync(byte[] buffer, int offset, int length) - { - return this.Client.SendAsync(buffer, offset, length); - } - - /// - public Task SendAsync(IRequestInfo requestInfo) - { - return this.Client.SendAsync(requestInfo); - } - - /// - public Task SendAsync(IList> transferBytes) - { - return this.Client.SendAsync(transferBytes); - } - - /// - public int SetBufferLength(int value) - { - return this.Client.SetBufferLength(value); - } - - /// - public void SetDataHandlingAdapter(TcpDataHandlingAdapter adapter) - { - this.Client.SetDataHandlingAdapter(adapter); - } - - /// - public ITcpClient Setup(TouchSocketConfig config) - { - this.JRPT = config.GetValue(JsonRpcConfigExtensions.JRPTProperty); - switch (this.JRPT) - { - case JRPT.Http: - this.Client ??= new HttpClient(); - break; - - case JRPT.Websocket: - this.Client ??= new WebSocketClient(); - break; - - case JRPT.Tcp: - default: - this.Client ??= new Sockets.TcpClient(); - break; - } - return this.Client.Setup(config); - } - - /// - public ITcpClient Setup(string ipHost) - { - var config = new TouchSocketConfig(); - config.SetRemoteIPHost(new IPHost(ipHost)); - return this.Setup(config); - } - - /// - public DependencyObject SetValue(IDependencyProperty dp, TValue value) - { - return this.Client.SetValue(dp, value); - } - - /// - public bool TryGetValue(IDependencyProperty dp, out TValue value) - { - return this.Client.TryGetValue(dp, out value); - } - - /// - public bool TryRemoveValue(IDependencyProperty dp, out TValue value) - { - return this.Client.TryRemoveValue(dp, out value); - } - - /// - /// 处理数据 - /// - /// - /// - private bool HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo) - { - string jsonString = null; - switch (this.JRPT) - { - case JRPT.Http: - { - var httpResponse = (HttpResponse)requestInfo; - jsonString = httpResponse.GetBody(); - break; - } - case JRPT.Websocket: - { - if (requestInfo is WSDataFrame dataFrame && dataFrame.Opcode == WSDataType.Text) - { - jsonString = dataFrame.ToText(); - } - break; - } - case JRPT.Tcp: - default: - { - if (byteBlock == null) - { - if (requestInfo is IJsonRpcRequestInfo jsonRpcRequest) - { - jsonString = jsonRpcRequest.GetJsonRpcString(); - } - } - else - { - jsonString = byteBlock.ToString(); - } - break; - } - } - - if (string.IsNullOrEmpty(jsonString)) - { - return true; - } - - try - { - if (jsonString.Contains("error") || jsonString.Contains("result")) - { - var responseContext = jsonString.FromJson(); - if (responseContext != null && !responseContext.id.IsNullOrEmpty()) - { - var waitContext = new JsonRpcWaitResult - { - Status = 1, - Sign = long.Parse(responseContext.id), - error = responseContext.error, - Return = responseContext.result - }; - this.m_waitHandle.SetRun(waitContext); - } - } - } - catch - { - } - return true; - } - } -} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Components/TcpJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Components/TcpJsonRpcClient.cs new file mode 100644 index 000000000..0747f6c23 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Components/TcpJsonRpcClient.cs @@ -0,0 +1,321 @@ +using System; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// 基于Tcp协议的TcpJsonRpc客户端 + /// + public class TcpJsonRpcClient : TcpClientBase, ITcpJsonRpcClient + { + private readonly WaitHandlePool m_waitHandle = new WaitHandlePool(); + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitSend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitSend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) + { + this.Invoke(method, invokeOption, ref parameters, null); + } + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + return this.Invoke(returnType, method, invokeOption, ref parameters, null); + } + + /// + public async Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitSend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + + /// + public async Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitSend: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + this.Send(SerializeConvert.JsonSerializeToBytes(jsonRpcRequest)); + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + + /// + protected override bool HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo) + { + string jsonString = null; + if (byteBlock == null) + { + if (requestInfo is IJsonRpcRequestInfo jsonRpcRequest) + { + jsonString = jsonRpcRequest.GetJsonRpcString(); + } + } + else + { + jsonString = byteBlock.ToString(); + } + + if (string.IsNullOrEmpty(jsonString)) + { + return base.HandleReceivedData(byteBlock, requestInfo); + } + + try + { + if (jsonString.Contains("error") || jsonString.Contains("result")) + { + var responseContext = jsonString.FromJson(); + if (responseContext != null && !responseContext.Id.IsNullOrEmpty()) + { + var waitContext = new JsonRpcWaitResult + { + Status = 1, + Sign = long.Parse(responseContext.Id), + Error = responseContext.Error, + Return = responseContext.Result + }; + this.m_waitHandle.SetRun(waitContext); + } + } + } + catch + { + } + return base.HandleReceivedData(byteBlock, requestInfo); + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Components/WebSocketJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Components/WebSocketJsonRpcClient.cs new file mode 100644 index 000000000..78b2d06de --- /dev/null +++ b/src/TouchSocket.JsonRpc/Components/WebSocketJsonRpcClient.cs @@ -0,0 +1,288 @@ +using System; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Http.WebSockets; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// 基于WebSocket协议的JsonRpc客户端。 + /// + public class WebSocketJsonRpcClient : WebSocketClientBase, IWebSocketJsonRpcClient + { + private readonly WaitHandlePool m_waitHandle = new WaitHandlePool(); + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + this.SendWithWS(jsonRpcRequest.ToJson()); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + case FeedbackType.WaitSend: + { + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitData(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + this.SendWithWS(jsonRpcRequest.ToJson()); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + case FeedbackType.WaitSend: + { + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + waitData.Wait(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + + /// + public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) + { + this.Invoke(method, invokeOption, ref parameters, null); + } + + /// + public object Invoke(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + return this.Invoke(returnType, method, invokeOption, ref parameters, null); + } + + /// + public async Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest() + { + Method = method, + Params = parameters + }; + + jsonRpcRequest.Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null; + this.SendWithWS(jsonRpcRequest.ToJson()); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + case FeedbackType.WaitSend: + { + this.m_waitHandle.Destroy(waitData); + return; + } + case FeedbackType.WaitInvoke: + { + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + break; + } + default: + return; + } + } + + /// + public async Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + { + var context = new JsonRpcWaitResult(); + var waitData = this.m_waitHandle.GetWaitDataAsync(context); + + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + parameters ??= new object[0]; + var jsonRpcRequest = new JsonRpcRequest + { + Method = method, + Params = parameters, + Id = invokeOption.FeedbackType == FeedbackType.WaitInvoke ? context.Sign.ToString() : null + }; + this.SendWithWS(jsonRpcRequest.ToJson()); + switch (invokeOption.FeedbackType) + { + case FeedbackType.OnlySend: + case FeedbackType.WaitSend: + { + this.m_waitHandle.Destroy(waitData); + return default; + } + case FeedbackType.WaitInvoke: + { + await waitData.WaitAsync(invokeOption.Timeout); + var resultContext = (JsonRpcWaitResult)waitData.WaitResult; + this.m_waitHandle.Destroy(waitData); + + if (resultContext.Status == 0) + { + throw new TimeoutException("等待结果超时"); + } + if (resultContext.Error != null) + { + throw new RpcException(resultContext.Error.Message); + } + + if (resultContext.Return == null) + { + return default; + } + else + { + if (returnType.IsPrimitive || returnType == typeof(string)) + { + return resultContext.Return.ToString().ParseToType(returnType); + } + else + { + return resultContext.Return.ToJson().FromJson(returnType); + } + } + } + default: + return default; + } + } + + /// + protected override bool HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo) + { + string jsonString = null; + if (requestInfo is WSDataFrame dataFrame && dataFrame.Opcode == WSDataType.Text) + { + jsonString = dataFrame.ToText(); + } + + if (string.IsNullOrEmpty(jsonString)) + { + return base.HandleReceivedData(byteBlock,requestInfo); + } + + try + { + if (jsonString.Contains("error") || jsonString.Contains("result")) + { + var responseContext = jsonString.FromJson(); + if (responseContext != null && !responseContext.Id.IsNullOrEmpty()) + { + var waitContext = new JsonRpcWaitResult + { + Status = 1, + Sign = long.Parse(responseContext.Id), + Error = responseContext.Error, + Return = responseContext.Result + }; + this.m_waitHandle.SetRun(waitContext); + } + } + } + catch + { + } + return base.HandleReceivedData(byteBlock, requestInfo); + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Config/JsonRpcConfigExtensions.cs b/src/TouchSocket.JsonRpc/Config/JsonRpcConfigExtensions.cs deleted file mode 100644 index 0aec6e967..000000000 --- a/src/TouchSocket.JsonRpc/Config/JsonRpcConfigExtensions.cs +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------------------------------------------ -// 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 -// 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 -// CSDN博客:https://blog.csdn.net/qq_40374647 -// 哔哩哔哩视频:https://space.bilibili.com/94253567 -// Gitee源代码仓库:https://gitee.com/RRQM_Home -// Github源代码仓库:https://github.com/RRQM -// API首页:http://rrqm_home.gitee.io/touchsocket/ -// 交流QQ群:234762506 -// 感谢您的下载和使用 -//------------------------------------------------------------------------------ -//------------------------------------------------------------------------------ -using System; -using TouchSocket.Core; -using TouchSocket.JsonRpc; - -namespace TouchSocket.Sockets -{ - /// - /// JsonRpcConfigExtensions - /// - public static class JsonRpcConfigExtensions - { - /// - /// 构建JsonRpc类客户端,并连接 - /// - /// - /// - /// - public static TClient BuildWithJsonRpcClient(this TouchSocketConfig config) where TClient : IJsonRpcClient,new() - { - return config.BuildClient(); - } - - /// - /// 构建JsonRpc类客户端,并连接 - /// - /// - /// - public static JsonRpcClient BuildWithJsonRpcClient(this TouchSocketConfig config) - { - return BuildWithJsonRpcClient(config); - } - - - /// - /// 设置JsonRpc的协议。 - /// - public static readonly DependencyProperty JRPTProperty = - DependencyProperty.Register("JRPT", JRPT.Tcp); - - /// - /// 设置JsonRpc的协议。默认为 - /// - /// - /// - /// - public static TouchSocketConfig SetJRPT(this TouchSocketConfig config, JRPT value) - { - config.SetValue(JRPTProperty, value); - return config; - } - } -} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Extensions/HttpSocketClientExtension.cs b/src/TouchSocket.JsonRpc/Extensions/HttpSocketClientExtension.cs new file mode 100644 index 000000000..2f9beb5b4 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Extensions/HttpSocketClientExtension.cs @@ -0,0 +1,38 @@ +using TouchSocket.Core; +using TouchSocket.Http; + +namespace TouchSocket.JsonRpc +{ + /// + /// HttpSocketClientExtension + /// + public static class HttpSocketClientExtension + { + /// + /// 标识是否为JsonRpc + /// + public static readonly DependencyProperty JsonRpcProperty = + DependencyProperty.Register("JsonRpc", false); + + /// + /// 获取 + /// + /// + /// + /// + public static bool GetJsonRpc(this IHttpSocketClient socketClient, bool value = true) + { + return socketClient.GetValue(JsonRpcProperty); + } + + /// + /// 设置 + /// + /// + /// + public static void SetJsonRpc(this IHttpSocketClient socketClient, bool value = true) + { + socketClient.SetValue(JsonRpcProperty, value); + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Extensions/JsonRpcConfigExtension.cs b/src/TouchSocket.JsonRpc/Extensions/JsonRpcConfigExtension.cs new file mode 100644 index 000000000..6a0bfe30f --- /dev/null +++ b/src/TouchSocket.JsonRpc/Extensions/JsonRpcConfigExtension.cs @@ -0,0 +1,86 @@ +//------------------------------------------------------------------------------ +// 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有 +// 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 +// CSDN博客:https://blog.csdn.net/qq_40374647 +// 哔哩哔哩视频:https://space.bilibili.com/94253567 +// Gitee源代码仓库:https://gitee.com/RRQM_Home +// Github源代码仓库:https://github.com/RRQM +// API首页:http://rrqm_home.gitee.io/touchsocket/ +// 交流QQ群:234762506 +// 感谢您的下载和使用 +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ +using TouchSocket.Core; +using TouchSocket.JsonRpc; + +namespace TouchSocket.Sockets +{ + /// + /// JsonRpcConfigExtension + /// + public static class JsonRpcConfigExtension + { + /// + /// 构建WebSocketJsonRpc类客户端,并连接 + /// + /// + /// + /// + public static TClient BuildWithWebSocketJsonRpcClient(this TouchSocketConfig config) where TClient : IWebSocketJsonRpcClient, new() + { + return config.BuildClient(); + } + + /// + /// 构建WebSocketJsonRpc类客户端,并连接 + /// + /// + /// + public static WebSocketJsonRpcClient BuildWithWebSocketJsonRpcClient(this TouchSocketConfig config) + { + return BuildWithWebSocketJsonRpcClient(config); + } + + /// + /// 构建HttpJsonRpc类客户端,并连接 + /// + /// + /// + /// + public static TClient BuildWithHttpJsonRpcClient(this TouchSocketConfig config) where TClient : IHttpJsonRpcClient, new() + { + return config.BuildClient(); + } + + /// + /// 构建HttpJsonRpc类客户端,并连接 + /// + /// + /// + public static HttpJsonRpcClient BuildWithHttpJsonRpcClient(this TouchSocketConfig config) + { + return BuildWithHttpJsonRpcClient(config); + } + + /// + /// 构建TcpJsonRpc类客户端,并连接 + /// + /// + /// + /// + public static TClient BuildWithTcpJsonRpcClient(this TouchSocketConfig config) where TClient : ITcpJsonRpcClient, new() + { + return config.BuildClient(); + } + + /// + /// 构建TcpJsonRpc类客户端,并连接 + /// + /// + /// + public static TcpJsonRpcClient BuildWithTcpJsonRpcClient(this TouchSocketConfig config) + { + return BuildWithTcpJsonRpcClient(config); + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Extensions/JsonRpcPluginsManagerExtension.cs b/src/TouchSocket.JsonRpc/Extensions/JsonRpcPluginsManagerExtension.cs index 4a6af759b..6fc282f7c 100644 --- a/src/TouchSocket.JsonRpc/Extensions/JsonRpcPluginsManagerExtension.cs +++ b/src/TouchSocket.JsonRpc/Extensions/JsonRpcPluginsManagerExtension.cs @@ -20,13 +20,33 @@ namespace TouchSocket.Core public static class JsonRpcPluginsManagerExtension { /// - /// 使用JsonRpc的插件。仅服务器可用。 + /// 使用基于Tcp协议的JsonRpc的插件。 /// /// /// - public static JsonRpcParserPlugin UseJsonRpc(this IPluginsManager pluginsManager) + public static TcpJsonRpcParserPlugin UseTcpJsonRpc(this IPluginsManager pluginsManager) { - return pluginsManager.Add(); + return pluginsManager.Add(); + } + + /// + /// 使用基于Http协议的JsonRpc的插件。仅服务器有用。 + /// + /// + /// + public static HttpJsonRpcParserPlugin UseHttpJsonRpc(this IPluginsManager pluginsManager) + { + return pluginsManager.Add(); + } + + /// + /// 使用基于WebSocket协议的JsonRpc的插件。 + /// + /// + /// + public static WebSocketJsonRpcParserPlugin UseWebSocketJsonRpc(this IPluginsManager pluginsManager) + { + return pluginsManager.Add(); } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcCallContext.cs new file mode 100644 index 000000000..e3fc88542 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcCallContext.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + /// + /// IHttpJsonRpcCallContext + /// + public interface IHttpJsonRpcCallContext: IJsonRpcCallContext + { + } +} diff --git a/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClient.cs new file mode 100644 index 000000000..8eda18a5d --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClient.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Http; + +namespace TouchSocket.JsonRpc +{ + /// + /// IHttpJsonRpcClient + /// + public interface IHttpJsonRpcClient:IJsonRpcClient,IHttpClient + { + } +} diff --git a/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClientSlim.cs b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClientSlim.cs new file mode 100644 index 000000000..fe9616098 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/IHttpJsonRpcClientSlim.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + /// + /// IHttpJsonRpcClientSlim + /// + public interface IHttpJsonRpcClientSlim:IJsonRpcClient + { + } +} diff --git a/src/TouchSocket.JsonRpc/Interface/IJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Interface/IJsonRpcCallContext.cs index 4271bb33f..0c98ba470 100644 --- a/src/TouchSocket.JsonRpc/Interface/IJsonRpcCallContext.cs +++ b/src/TouchSocket.JsonRpc/Interface/IJsonRpcCallContext.cs @@ -10,6 +10,7 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ +using TouchSocket.Rpc; using TouchSocket.WebApi; namespace TouchSocket.JsonRpc @@ -17,7 +18,7 @@ namespace TouchSocket.JsonRpc /// /// IJsonRpcCallContext /// - public interface IJsonRpcCallContext : IHttpCallContext + public interface IJsonRpcCallContext:ICallContext { /// /// Json字符串 @@ -28,10 +29,5 @@ namespace TouchSocket.JsonRpc /// JsonRpc数据包 /// public JsonRpcContext JsonRpcContext { get; } - - /// - /// 表明当前的调用协议。 - /// - JRPT JRPT { get; } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Interface/IJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Interface/IJsonRpcClient.cs index 5b0b63238..0e657c9c2 100644 --- a/src/TouchSocket.JsonRpc/Interface/IJsonRpcClient.cs +++ b/src/TouchSocket.JsonRpc/Interface/IJsonRpcClient.cs @@ -18,7 +18,7 @@ namespace TouchSocket.JsonRpc /// /// IJsonRpcClient /// - public interface IJsonRpcClient : ITcpClient, IRpcClient + public interface IJsonRpcClient : IRpcClient { } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Interface/IJsonRpcRequestInfo.cs b/src/TouchSocket.JsonRpc/Interface/IJsonRpcRequestInfo.cs index 144f153c2..289f3ed24 100644 --- a/src/TouchSocket.JsonRpc/Interface/IJsonRpcRequestInfo.cs +++ b/src/TouchSocket.JsonRpc/Interface/IJsonRpcRequestInfo.cs @@ -10,7 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using TouchSocket.Core; namespace TouchSocket.JsonRpc { diff --git a/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcCallContext.cs b/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcCallContext.cs new file mode 100644 index 000000000..2a9789e92 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcCallContext.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TouchSocket.JsonRpc +{ + /// + /// ITcpJsonRpcCallContext + /// + public interface ITcpJsonRpcCallContext:IJsonRpcCallContext + { + } +} diff --git a/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcClient.cs new file mode 100644 index 000000000..0a4ae9be9 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/ITcpJsonRpcClient.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + public interface ITcpJsonRpcClient:IJsonRpcClient,ITcpClient + { + } +} diff --git a/src/TouchSocket.JsonRpc/Interface/IWebSocketJsonRpcClient.cs b/src/TouchSocket.JsonRpc/Interface/IWebSocketJsonRpcClient.cs new file mode 100644 index 000000000..61a1f1173 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Interface/IWebSocketJsonRpcClient.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using TouchSocket.Http.WebSockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// IWebSocketJsonRpcClient + /// + public interface IWebSocketJsonRpcClient: IWebSocketClient, IJsonRpcClient + { + } +} diff --git a/src/TouchSocket.JsonRpc/Plugins/HttpJsonRpcParserPlugin.cs b/src/TouchSocket.JsonRpc/Plugins/HttpJsonRpcParserPlugin.cs new file mode 100644 index 000000000..18ea1fca0 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Plugins/HttpJsonRpcParserPlugin.cs @@ -0,0 +1,91 @@ +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Http; + +namespace TouchSocket.JsonRpc +{ + /// + /// HttpJsonRpcParserPlugin + /// + [PluginOption(Singleton = true, NotRegister = false)] + public sealed class HttpJsonRpcParserPlugin : JsonRpcParserPluginBase, IHttpPostPlugin + { + private string m_jsonRpcUrl = "/jsonrpc"; + + /// + /// HttpJsonRpcParserPlugin + /// + /// + public HttpJsonRpcParserPlugin(IContainer container) : base(container) + { + } + + /// + /// 当挂载在时,匹配Url然后响应。当设置为null或空时,会全部响应。 + /// + public string JsonRpcUrl + { + get => this.m_jsonRpcUrl; + set => this.m_jsonRpcUrl = string.IsNullOrEmpty(value) ? "/" : value; + } + + async Task IHttpPostPlugin.OnHttpPost(IHttpSocketClient client, HttpContextEventArgs e) + { + if (this.m_jsonRpcUrl == "/" || e.Context.Request.UrlEquals(this.m_jsonRpcUrl)) + { + e.Handled = true; + this.ThisInvoke(new HttpJsonRpcCallContext(client, e.Context.Request.GetBody(), e.Context)); + } + else + { + await e.InvokeNext(); + } + } + + /// + /// 当挂载在时,匹配Url然后响应。当设置为null或空时,会全部响应。 + /// + /// + /// + public HttpJsonRpcParserPlugin SetJsonRpcUrl(string jsonRpcUrl) + { + this.JsonRpcUrl = jsonRpcUrl; + return this; + } + + /// + protected override sealed void Response(JsonRpcCallContextBase callContext, object result, JsonRpcError error) + { + try + { + using (var responseByteBlock = new ByteBlock()) + { + object jobject; + if (error == null) + { + jobject = new JsonRpcSuccessResponse + { + result = result, + id = callContext.JsonRpcContext.Id + }; + } + else + { + jobject = new JsonRpcErrorResponse + { + error = error, + id = callContext.JsonRpcContext.Id + }; + } + + var httpResponse = ((HttpJsonRpcCallContext)callContext).HttpContext.Response; + httpResponse.FromJson(jobject.ToJson()); + httpResponse.Answer(); + } + } + catch + { + } + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPlugin.cs b/src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPluginBase.cs similarity index 51% rename from src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPlugin.cs rename to src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPluginBase.cs index d08dee88a..8eba6b1be 100644 --- a/src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPlugin.cs +++ b/src/TouchSocket.JsonRpc/Plugins/JsonRpcParserPluginBase.cs @@ -14,26 +14,22 @@ using System; using System.Collections; using System.Collections.Generic; -using System.Threading.Tasks; using TouchSocket.Core; using TouchSocket.Http; -using TouchSocket.Http.WebSockets; using TouchSocket.Rpc; -using TouchSocket.Sockets; namespace TouchSocket.JsonRpc { /// /// JsonRpcParser解析器插件 /// - public class JsonRpcParserPlugin : PluginBase, IRpcParser, ITcpConnectingPlugin, IHttpPostPlugin, ITcpReceivedPlugin, IWebsocketReceivedPlugin + [PluginOption(Singleton = true, NotRegister = false)] + public abstract class JsonRpcParserPluginBase : PluginBase, IRpcParser { - private string m_jsonRpcUrl = "/jsonrpc"; - /// /// 构造函数 /// - public JsonRpcParserPlugin(IContainer container) + public JsonRpcParserPluginBase(IContainer container) { if (container.IsRegistered(typeof(RpcStore))) { @@ -52,36 +48,11 @@ namespace TouchSocket.JsonRpc /// public ActionMap ActionMap { get; private set; } - /// - /// 自动转换协议 - /// - public bool AutoSwitch { get; set; } = true; - - /// - /// 当挂载在时,匹配Url然后响应。当设置为null或空时,会全部响应。 - /// - public string JsonRpcUrl - { - get => this.m_jsonRpcUrl; - set => this.m_jsonRpcUrl = string.IsNullOrEmpty(value) ? "/" : value; - } - /// /// /// public RpcStore RpcStore { get; private set; } - /// - /// 不需要自动转化协议。 - /// 仅当服务器是TCP时生效。此时如果携带协议为TcpJsonRpc时才会解释为jsonRpc。 - /// - /// - public JsonRpcParserPlugin NoSwitchProtocol() - { - this.AutoSwitch = false; - return this; - } - #region RPC解析器 void IRpcParser.OnRegisterServer(MethodInstance[] methodInstances) @@ -108,233 +79,19 @@ namespace TouchSocket.JsonRpc #endregion RPC解析器 - async Task IHttpPostPlugin.OnHttpPost(IHttpSocketClient client, HttpContextEventArgs e) - { - if (this.m_jsonRpcUrl == "/" || e.Context.Request.UrlEquals(this.m_jsonRpcUrl)) - { - e.Handled = true; - this.ThisInvoke(new JsonRpcCallContext() - { - Caller = client, - JRPT = JRPT.Http, - JsonString = e.Context.Request.GetBody(), - HttpContext = e.Context - }); - } - else - { - await e.InvokeNext(); - } - } - - async Task ITcpConnectingPlugin.OnTcpConnecting(IClient client, ConnectingEventArgs e) - { - if (this.AutoSwitch && client.Protocol == Protocol.TCP) - { - client.Protocol = JsonRpcUtility.JsonRpc; - } - - await e.InvokeNext(); - } - - async Task ITcpReceivedPlugin.OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e) - { - if (client.Protocol == JsonRpcUtility.JsonRpc) - { - if (e.ByteBlock != null) - { - var jsonRpcStr = e.ByteBlock.ToString(); - if (jsonRpcStr.Contains("jsonrpc")) - { - e.Handled = true; - this.ThisInvoke(new JsonRpcCallContext() - { - Caller = client, - JRPT = JRPT.Tcp, - JsonString = e.ByteBlock.ToString() - }); - - return; - } - } - } - - await e.InvokeNext(); - } - - async Task IWebsocketReceivedPlugin.OnWebsocketReceived(IHttpClientBase client, WSDataFrameEventArgs e) - { - if (e.DataFrame.Opcode == WSDataType.Text) - { - var jsonRpcStr = e.DataFrame.ToText(); - if (jsonRpcStr.Contains("jsonrpc")) - { - e.Handled = true; - this.ThisInvoke(new JsonRpcCallContext() - { - Caller = client, - JRPT = JRPT.Websocket, - JsonString = jsonRpcStr - }); - - return; - } - } - else - { - await e.InvokeNext(); - } - } + /// + /// 处理响应结果。 + /// + /// + /// + /// + protected abstract void Response(JsonRpcCallContextBase callContext, object result, JsonRpcError error); /// - /// 当挂载在时,匹配Url然后响应。当设置为null或空时,会全部响应。 + /// 调用JsonRpc /// - /// - /// - public JsonRpcParserPlugin SetJsonRpcUrl(string jsonRpcUrl) - { - this.JsonRpcUrl = jsonRpcUrl; - return this; - } - - private static void Response(JsonRpcCallContext callContext, object result, error error) - { - try - { - using (var responseByteBlock = new ByteBlock()) - { - object jobject; - if (error == null) - { - jobject = new JsonRpcSuccessResponse - { - result = result, - id = callContext.JsonRpcContext.id - }; - } - else - { - jobject = new JsonRpcErrorResponse - { - error = error, - id = callContext.JsonRpcContext.id - }; - } - - var client = (ITcpClientBase)callContext.Caller; - if (callContext.JRPT == JRPT.Http) - { - var httpResponse = callContext.HttpContext.Response; - httpResponse.FromJson(jobject.ToJson()); - httpResponse.Answer(); - } - else if (callContext.JRPT == JRPT.Websocket) - { - ((HttpSocketClient)client).SendWithWS(jobject.ToJson()); - } - else - { - responseByteBlock.Write(jobject.ToJson().ToUTF8Bytes()); - client.Send(responseByteBlock); - } - } - } - catch - { - } - } - - private void BuildRequestContext(ref JsonRpcCallContext callContext) - { - var jsonRpcContext = SerializeConvert.JsonDeserializeFromString(callContext.JsonString); - callContext.JsonRpcContext = jsonRpcContext; - if (jsonRpcContext.id != null) - { - jsonRpcContext.needResponse = true; - } - - if (this.ActionMap.TryGetMethodInstance(jsonRpcContext.method, out var methodInstance)) - { - callContext.MethodInstance = methodInstance; - if (jsonRpcContext.@params == null) - { - if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) - { - jsonRpcContext.parameters = methodInstance.ParameterNames.Length > 1 ? throw new RpcException("调用参数计数不匹配") : (new object[] { callContext }); - } - else - { - if (methodInstance.ParameterNames.Length != 0) - { - throw new RpcException("调用参数计数不匹配"); - } - } - } - if (jsonRpcContext.@params is Dictionary obj) - { - jsonRpcContext.parameters = new object[methodInstance.ParameterNames.Length]; - //内联 - var i = 0; - if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) - { - jsonRpcContext.parameters[0] = callContext; - i = 1; - } - for (; i < methodInstance.ParameterNames.Length; i++) - { - if (obj.TryGetValue(methodInstance.ParameterNames[i], out var jToken)) - { - var type = methodInstance.ParameterTypes[i]; - jsonRpcContext.parameters[i] = jToken.ToJson().FromJson(type); - } - else - { - if (methodInstance.Parameters[i].HasDefaultValue) - { - jsonRpcContext.parameters[i] = methodInstance.Parameters[i].DefaultValue; - } - else - { - throw new RpcException("调用参数计数不匹配"); - } - } - } - } - else - { - var array = (IList)jsonRpcContext.@params; - if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) - { - if (array.Count != methodInstance.ParameterNames.Length - 1) - { - throw new RpcException("调用参数计数不匹配"); - } - jsonRpcContext.parameters = new object[methodInstance.ParameterNames.Length]; - - jsonRpcContext.parameters[0] = callContext; - for (var i = 0; i < array.Count; i++) - { - jsonRpcContext.parameters[i + 1] = array[i].ToJson().FromJson(methodInstance.ParameterTypes[i + 1]); - } - } - else - { - if (array.Count != methodInstance.ParameterNames.Length) - { - throw new RpcException("调用参数计数不匹配"); - } - jsonRpcContext.parameters = new object[methodInstance.ParameterNames.Length]; - - for (var i = 0; i < array.Count; i++) - { - jsonRpcContext.parameters[i] = array[i].ToJson().FromJson(methodInstance.ParameterTypes[i]); - } - } - } - } - } - - private void ThisInvoke(JsonRpcCallContext callContext) + /// + protected void ThisInvoke(JsonRpcCallContextBase callContext) { var invokeResult = new InvokeResult(); @@ -362,20 +119,20 @@ namespace TouchSocket.JsonRpc if (invokeResult.Status == InvokeStatus.Ready) { - var rpcServer = callContext.MethodInstance.ServerFactory.Create(callContext, callContext.JsonRpcContext.parameters); + var rpcServer = callContext.MethodInstance.ServerFactory.Create(callContext, callContext.JsonRpcContext.Parameters); if (rpcServer is ITransientRpcServer transientRpcServer) { transientRpcServer.CallContext = callContext; } - invokeResult = RpcStore.Execute(rpcServer, callContext.JsonRpcContext.parameters, callContext); + invokeResult = RpcStore.Execute(rpcServer, callContext.JsonRpcContext.Parameters, callContext); } - if (!callContext.JsonRpcContext.needResponse) + if (!callContext.JsonRpcContext.NeedResponse) { return; } - error error = null; + JsonRpcError error = null; switch (invokeResult.Status) { case InvokeStatus.Success: @@ -384,37 +141,135 @@ namespace TouchSocket.JsonRpc } case InvokeStatus.UnFound: { - error = new error(); - error.code = -32601; - error.message = "函数未找到"; + error = new JsonRpcError + { + Code = -32601, + Message = "函数未找到" + }; break; } case InvokeStatus.UnEnable: { - error = new error(); - error.code = -32601; - error.message = "函数已被禁用"; + error = new JsonRpcError + { + Code = -32601, + Message = "函数已被禁用" + }; break; } case InvokeStatus.InvocationException: { - error = new error(); - error.code = -32603; - error.message = "函数内部异常"; + error = new JsonRpcError + { + Code = -32603, + Message = "函数内部异常" + }; break; } case InvokeStatus.Exception: { - error = new error(); - error.code = -32602; - error.message = invokeResult.Message; + error = new JsonRpcError + { + Code = -32602, + Message = invokeResult.Message + }; break; } default: return; } - Response(callContext, invokeResult.Result, error); + this.Response(callContext, invokeResult.Result, error); + } + + private void BuildRequestContext(ref JsonRpcCallContextBase callContext) + { + var jsonRpcContext = SerializeConvert.JsonDeserializeFromString(callContext.JsonString); + callContext.JsonRpcContext = jsonRpcContext; + if (jsonRpcContext.Id != null) + { + jsonRpcContext.NeedResponse = true; + } + + if (this.ActionMap.TryGetMethodInstance(jsonRpcContext.Method, out var methodInstance)) + { + callContext.MethodInstance = methodInstance; + if (jsonRpcContext.Params == null) + { + if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) + { + jsonRpcContext.Parameters = methodInstance.ParameterNames.Length > 1 ? throw new RpcException("调用参数计数不匹配") : (new object[] { callContext }); + } + else + { + if (methodInstance.ParameterNames.Length != 0) + { + throw new RpcException("调用参数计数不匹配"); + } + } + } + if (jsonRpcContext.Params is Dictionary obj) + { + jsonRpcContext.Parameters = new object[methodInstance.ParameterNames.Length]; + //内联 + var i = 0; + if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) + { + jsonRpcContext.Parameters[0] = callContext; + i = 1; + } + for (; i < methodInstance.ParameterNames.Length; i++) + { + if (obj.TryGetValue(methodInstance.ParameterNames[i], out var jToken)) + { + var type = methodInstance.ParameterTypes[i]; + jsonRpcContext.Parameters[i] = jToken.ToJson().FromJson(type); + } + else + { + if (methodInstance.Parameters[i].HasDefaultValue) + { + jsonRpcContext.Parameters[i] = methodInstance.Parameters[i].DefaultValue; + } + else + { + throw new RpcException("调用参数计数不匹配"); + } + } + } + } + else + { + var array = (IList)jsonRpcContext.Params; + if (methodInstance.MethodFlags.HasFlag(MethodFlags.IncludeCallContext)) + { + if (array.Count != methodInstance.ParameterNames.Length - 1) + { + throw new RpcException("调用参数计数不匹配"); + } + jsonRpcContext.Parameters = new object[methodInstance.ParameterNames.Length]; + + jsonRpcContext.Parameters[0] = callContext; + for (var i = 0; i < array.Count; i++) + { + jsonRpcContext.Parameters[i + 1] = array[i].ToJson().FromJson(methodInstance.ParameterTypes[i + 1]); + } + } + else + { + if (array.Count != methodInstance.ParameterNames.Length) + { + throw new RpcException("调用参数计数不匹配"); + } + jsonRpcContext.Parameters = new object[methodInstance.ParameterNames.Length]; + + for (var i = 0; i < array.Count; i++) + { + jsonRpcContext.Parameters[i] = array[i].ToJson().FromJson(methodInstance.ParameterTypes[i]); + } + } + } + } } } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Plugins/TcpJsonRpcParserPlugin.cs b/src/TouchSocket.JsonRpc/Plugins/TcpJsonRpcParserPlugin.cs new file mode 100644 index 000000000..8a90616b9 --- /dev/null +++ b/src/TouchSocket.JsonRpc/Plugins/TcpJsonRpcParserPlugin.cs @@ -0,0 +1,103 @@ +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// 基于Tcp协议的JsonRpc功能插件 + /// + [PluginOption(Singleton = true, NotRegister = false)] + public sealed class TcpJsonRpcParserPlugin : JsonRpcParserPluginBase, ITcpConnectingPlugin, ITcpReceivedPlugin + { + /// + /// 基于Tcp协议的JsonRpc功能插件 + /// + /// + public TcpJsonRpcParserPlugin(IContainer container) : base(container) + { + } + + /// + /// 自动转换协议 + /// + public bool AutoSwitch { get; set; } = true; + + /// + /// 不需要自动转化协议。 + /// 仅当服务器是TCP时生效。此时如果携带协议为TcpJsonRpc时才会解释为jsonRpc。 + /// + /// + public TcpJsonRpcParserPlugin NoSwitchProtocol() + { + this.AutoSwitch = false; + return this; + } + + Task ITcpConnectingPlugin.OnTcpConnecting(IClient client, ConnectingEventArgs e) + { + if (this.AutoSwitch && client.Protocol == Protocol.TCP) + { + client.Protocol = JsonRpcUtility.TcpJsonRpc; + } + + return e.InvokeNext(); + } + + async Task ITcpReceivedPlugin.OnTcpReceived(ITcpClientBase client, ReceivedDataEventArgs e) + { + if (client.Protocol == JsonRpcUtility.TcpJsonRpc) + { + var jsonRpcStr = string.Empty; + if (e.RequestInfo is IJsonRpcRequestInfo requestInfo) + { + jsonRpcStr = requestInfo.GetJsonRpcString(); + } + else if (e.ByteBlock != null) + { + jsonRpcStr = e.ByteBlock.ToString(); + } + + if (jsonRpcStr.HasValue()) + { + e.Handled = true; + this.ThisInvoke(new TcpJsonRpcCallContext(client, jsonRpcStr)); + return; + } + } + + await e.InvokeNext(); + } + + /// + protected override sealed void Response(JsonRpcCallContextBase callContext, object result, JsonRpcError error) + { + try + { + object jobject; + if (error == null) + { + jobject = new JsonRpcSuccessResponse + { + result = result, + id = callContext.JsonRpcContext.Id + }; + } + else + { + jobject = new JsonRpcErrorResponse + { + error = error, + id = callContext.JsonRpcContext.Id + }; + } + + var client = (ITcpClientBase)callContext.Caller; + client.Send(jobject.ToJson().ToUTF8Bytes()); + } + catch + { + } + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Plugins/WebSocketJsonRpcParserPlugin.cs b/src/TouchSocket.JsonRpc/Plugins/WebSocketJsonRpcParserPlugin.cs new file mode 100644 index 000000000..8ae03d2ef --- /dev/null +++ b/src/TouchSocket.JsonRpc/Plugins/WebSocketJsonRpcParserPlugin.cs @@ -0,0 +1,98 @@ +using System; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Http; +using TouchSocket.Http.WebSockets; +using TouchSocket.Sockets; + +namespace TouchSocket.JsonRpc +{ + /// + /// WebSocketJsonRpcParserPlugin + /// + [PluginOption(Singleton = true, NotRegister = false)] + public sealed class WebSocketJsonRpcParserPlugin : JsonRpcParserPluginBase, IWebSocketReceivedPlugin, IWebSocketHandshakedPlugin + { + /// + /// WebSocketJsonRpcParserPlugin + /// + /// + public WebSocketJsonRpcParserPlugin(IContainer container) : base(container) + { + } + + /// + /// 经过判断是否标识当前的客户端为JsonRpc + /// + public Func> AllowJsonRpc { get; set; } + + async Task IWebSocketHandshakedPlugin.OnWebSocketHandshaked(IHttpSocketClient client, HttpContextEventArgs e) + { + if (this.AllowJsonRpc != null) + { + if (await this.AllowJsonRpc.Invoke(client, e.Context)) + { + client.SetJsonRpc(); + } + } + } + + async Task IWebSocketReceivedPlugin.OnWebSocketReceived(IHttpSocketClient client, WSDataFrameEventArgs e) + { + if (e.DataFrame.Opcode == WSDataType.Text && client.GetJsonRpc()) + { + var jsonRpcStr = e.DataFrame.ToText(); + e.Handled = true; + this.ThisInvoke(new WebSocketJsonRpcCallContext(client, jsonRpcStr)); + } + else + { + await e.InvokeNext(); + } + } + + /// + /// 经过判断是否标识当前的客户端为JsonRpc + /// + /// + /// + public WebSocketJsonRpcParserPlugin SetAllowSwitchProtocol(Func> allowJsonRpc) + { + this.AllowJsonRpc = allowJsonRpc; + return this; + } + + /// + protected override sealed void Response(JsonRpcCallContextBase callContext, object result, JsonRpcError error) + { + try + { + using (var responseByteBlock = new ByteBlock()) + { + object jobject; + if (error == null) + { + jobject = new JsonRpcSuccessResponse + { + result = result, + id = callContext.JsonRpcContext.Id + }; + } + else + { + jobject = new JsonRpcErrorResponse + { + error = error, + id = callContext.JsonRpcContext.Id + }; + } + + ((IHttpSocketClient)callContext.Caller).SendWithWS(jobject.ToJson()); + } + } + catch + { + } + } + } +} \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/Resources/TouchSocketJsonRpcResource.cs b/src/TouchSocket.JsonRpc/Resources/TouchSocketJsonRpcResource.cs index fcf62c131..30ec31e17 100644 --- a/src/TouchSocket.JsonRpc/Resources/TouchSocketJsonRpcResource.cs +++ b/src/TouchSocket.JsonRpc/Resources/TouchSocketJsonRpcResource.cs @@ -11,8 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.ComponentModel; - namespace TouchSocket.Resources { /// @@ -20,6 +18,6 @@ namespace TouchSocket.Resources /// public enum TouchSocketJsonRpcResource { - + } } \ No newline at end of file diff --git a/src/TouchSocket.JsonRpc/TouchSocket.JsonRpc.csproj b/src/TouchSocket.JsonRpc/TouchSocket.JsonRpc.csproj index 8362b4812..c1b665169 100644 --- a/src/TouchSocket.JsonRpc/TouchSocket.JsonRpc.csproj +++ b/src/TouchSocket.JsonRpc/TouchSocket.JsonRpc.csproj @@ -1,56 +1,21 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 JsonRpc - - 这是基于TouchSocket,能够提供JsonRpc的扩展功能组件。 + 这是基于TouchSocket,能够提供JsonRpc的扩展功能组件。 - 说明文档:http://rrqm_home.gitee.io/touchsocket - - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt +说明文档:http://rrqm_home.gitee.io/touchsocket TouchSocket.JsonRpc - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.JsonRpc + ..\..\Build\NugetPackages\TouchSocket.JsonRpc - - True - - - - True - - - - - - - - - - - - - + + + True + Embedded + True + diff --git a/src/TouchSocket.Rpc/Attribute/GeneratorRpcMethodAttribute.cs b/src/TouchSocket.Rpc/Attribute/GeneratorRpcMethodAttribute.cs index 096519089..6812f8435 100644 --- a/src/TouchSocket.Rpc/Attribute/GeneratorRpcMethodAttribute.cs +++ b/src/TouchSocket.Rpc/Attribute/GeneratorRpcMethodAttribute.cs @@ -1,5 +1,4 @@ using System; -using TouchSocket.Core; namespace TouchSocket.Rpc { diff --git a/src/TouchSocket.Rpc/Attribute/GeneratorRpcProxyAttribute.cs b/src/TouchSocket.Rpc/Attribute/GeneratorRpcProxyAttribute.cs index 644095081..50c99ab25 100644 --- a/src/TouchSocket.Rpc/Attribute/GeneratorRpcProxyAttribute.cs +++ b/src/TouchSocket.Rpc/Attribute/GeneratorRpcProxyAttribute.cs @@ -1,5 +1,4 @@ using System; -using TouchSocket.Core; namespace TouchSocket.Rpc { diff --git a/src/TouchSocket.Rpc/Code/CodeGenerator.cs b/src/TouchSocket.Rpc/Code/CodeGenerator.cs index a3b5db0cb..a1f45f430 100644 --- a/src/TouchSocket.Rpc/Code/CodeGenerator.cs +++ b/src/TouchSocket.Rpc/Code/CodeGenerator.cs @@ -162,7 +162,6 @@ namespace TouchSocket.Rpc codeString.AppendLine("using TouchSocket.Core;"); codeString.AppendLine("using TouchSocket.Sockets;"); codeString.AppendLine("using TouchSocket.Rpc;"); - codeString.AppendLine("using TouchSocket.Dmtp.Rpc;"); codeString.AppendLine("using System.Collections.Generic;"); codeString.AppendLine("using System.Diagnostics;"); codeString.AppendLine("using System.Text;"); diff --git a/src/TouchSocket.Rpc/Common/ActionMap.cs b/src/TouchSocket.Rpc/Common/ActionMap.cs index e752f8168..ca68631e9 100644 --- a/src/TouchSocket.Rpc/Common/ActionMap.cs +++ b/src/TouchSocket.Rpc/Common/ActionMap.cs @@ -24,7 +24,7 @@ namespace TouchSocket.Rpc /// 服务映射图 /// /// - public ActionMap(bool ignoreCase):base(ignoreCase?StringComparer.OrdinalIgnoreCase: StringComparer.Ordinal) + public ActionMap(bool ignoreCase) : base(ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal) { } diff --git a/src/TouchSocket.Rpc/Common/InvokeOption.cs b/src/TouchSocket.Rpc/Common/InvokeOption.cs index 14e65b4e9..52082d8e9 100644 --- a/src/TouchSocket.Rpc/Common/InvokeOption.cs +++ b/src/TouchSocket.Rpc/Common/InvokeOption.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using TouchSocket.Core; +using System.Threading; namespace TouchSocket.Rpc { diff --git a/src/TouchSocket.Rpc/Extensions/RpcParserExtension.cs b/src/TouchSocket.Rpc/Extensions/RpcParserExtension.cs index 342ff25ed..72f788811 100644 --- a/src/TouchSocket.Rpc/Extensions/RpcParserExtension.cs +++ b/src/TouchSocket.Rpc/Extensions/RpcParserExtension.cs @@ -1,9 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Text; -using System.Threading.Tasks; namespace TouchSocket.Rpc { @@ -19,7 +14,7 @@ namespace TouchSocket.Rpc /// /// /// - public static TParser ConfigureRpcStore(this TParser parser , Action action)where TParser :IRpcParser + public static TParser ConfigureRpcStore(this TParser parser, Action action) where TParser : IRpcParser { action?.Invoke(parser.RpcStore); return parser; diff --git a/src/TouchSocket.Rpc/Extensions/RpcPluginsManagerExtension.cs b/src/TouchSocket.Rpc/Extensions/RpcPluginsManagerExtension.cs index e8696eee6..7b5fa603b 100644 --- a/src/TouchSocket.Rpc/Extensions/RpcPluginsManagerExtension.cs +++ b/src/TouchSocket.Rpc/Extensions/RpcPluginsManagerExtension.cs @@ -27,7 +27,7 @@ namespace TouchSocket.Core /// public static GlobalRpcStorePlugin UseGlobalRpcStore(this IPluginsManager pluginsManager) { - return pluginsManager.Add(); + return pluginsManager.Add(); } /// @@ -36,9 +36,9 @@ namespace TouchSocket.Core /// /// /// - public static GlobalRpcStorePlugin UseGlobalRpcStore(this IPluginsManager pluginsManager,Action action) + public static GlobalRpcStorePlugin UseGlobalRpcStore(this IPluginsManager pluginsManager, Action action) { - var plugin= pluginsManager.Add(); + var plugin = pluginsManager.Add(); plugin.ConfigureRpcStore(action); return plugin; } diff --git a/src/TouchSocket.Rpc/Interface/IRpcClient.cs b/src/TouchSocket.Rpc/Interface/IRpcClient.cs index 11e8e7be7..5c14abdf9 100644 --- a/src/TouchSocket.Rpc/Interface/IRpcClient.cs +++ b/src/TouchSocket.Rpc/Interface/IRpcClient.cs @@ -47,7 +47,7 @@ namespace TouchSocket.Rpc /// Rpc异常 /// 其他异常 /// 服务器返回结果 - object Invoke(Type returnType,string invokeKey, IInvokeOption invokeOption, params object[] parameters); + object Invoke(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters); /// /// Rpc调用 diff --git a/src/TouchSocket.Rpc/Interface/ITargetRpcClient.cs b/src/TouchSocket.Rpc/Interface/ITargetRpcClient.cs index 04aa7a3d5..b0965156a 100644 --- a/src/TouchSocket.Rpc/Interface/ITargetRpcClient.cs +++ b/src/TouchSocket.Rpc/Interface/ITargetRpcClient.cs @@ -12,7 +12,6 @@ //------------------------------------------------------------------------------ using System; using System.Threading.Tasks; -using TouchSocket.Rpc; using TouchSocket.Sockets; namespace TouchSocket.Rpc @@ -48,7 +47,7 @@ namespace TouchSocket.Rpc /// 没有找到Id对应的客户端 /// 其他异常 /// 返回值 - Task InvokeAsync(Type returnType,string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters); + Task InvokeAsync(Type returnType, string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters); /// /// 调用对应Id的客户端Rpc @@ -76,7 +75,7 @@ namespace TouchSocket.Rpc /// 没有找到Id对应的客户端 /// 其他异常 /// 返回值 - object Invoke(Type returnType,string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters); + object Invoke(Type returnType, string targetId, string invokeKey, IInvokeOption invokeOption, params object[] parameters); /// /// 调用对应Id的客户端Rpc diff --git a/src/TouchSocket.Rpc/Resources/TouchSocketRpcResource.cs b/src/TouchSocket.Rpc/Resources/TouchSocketRpcResource.cs index a1d5a13c0..33cdcd480 100644 --- a/src/TouchSocket.Rpc/Resources/TouchSocketRpcResource.cs +++ b/src/TouchSocket.Rpc/Resources/TouchSocketRpcResource.cs @@ -11,8 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.ComponentModel; - namespace TouchSocket.Resources { /// diff --git a/src/TouchSocket.Rpc/TouchSocket.Rpc.csproj b/src/TouchSocket.Rpc/TouchSocket.Rpc.csproj index 2342f7822..010172b8b 100644 --- a/src/TouchSocket.Rpc/TouchSocket.Rpc.csproj +++ b/src/TouchSocket.Rpc/TouchSocket.Rpc.csproj @@ -1,51 +1,21 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 Rpc;CodeGenerator 这是基于TouchSocket的Rpc功能基础类。它能规范Rpc的调用、代理的生成、以及其他特性。 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt TouchSocket.Rpc - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.Rpc + ..\..\Build\NugetPackages\TouchSocket.Rpc - - True - - - - True - - - - - - - - - - + + + True + Embedded + True + diff --git a/src/TouchSocket.SourceGenerator.Rpc/LICENSE.txt b/src/TouchSocket.SourceGenerator.Rpc/LICENSE.txt new file mode 100644 index 000000000..b09cd7856 --- /dev/null +++ b/src/TouchSocket.SourceGenerator.Rpc/LICENSE.txt @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/TouchSocket.SourceGenerator.Rpc/TouchSocket.SourceGenerator.Rpc.csproj b/src/TouchSocket.SourceGenerator.Rpc/TouchSocket.SourceGenerator.Rpc.csproj index 3d29afd8d..3d4ab1c91 100644 --- a/src/TouchSocket.SourceGenerator.Rpc/TouchSocket.SourceGenerator.Rpc.csproj +++ b/src/TouchSocket.SourceGenerator.Rpc/TouchSocket.SourceGenerator.Rpc.csproj @@ -1,14 +1,14 @@  - 1.0.0.2 netstandard2.0 9.0 true + false + bin - diff --git a/src/TouchSocket.SourceGenerator.Rpc/logo.ico b/src/TouchSocket.SourceGenerator.Rpc/logo.ico new file mode 100644 index 0000000000000000000000000000000000000000..7b33dcf65b7f6de006c70d6438ca59dcf2f09643 GIT binary patch literal 16958 zcmds;4{Q`w9><453Te1vjM*5{aKtnhLYj-YGh9QAG)lJuTg0vLl=GAm1T244L?wu} zSfQd|`6mj!@*kmKfr16fvNOxU(#|x*7;_<{X`nG&Lr7E2#sHz)cb_-x^rqWwyR+Se z(`~kIW_ISi_nF`O^ZotijiLhx=k{weMHnSvJGR}j?e-Fx&?`OEYZ`IC)0_k%{= z(qZd41X^6&!zom$YYWA->3cU{McW>FO0+a!uaNC z-8eMGZ5*5?v$=1dP1*=Y0bH zm2vWamO_33ztH!3YV|#Z55y`bRmc9%_yzp`)^~aCS$}ZKe@cB>j(;1@s54)cHc3+Z zx9l(Zg}!TAo4(WYXsT>(&o=@7#d7{XG^}*UQV}{X`es+zP3*LQ2XrcM}akGS81!ymTRj#Rz6Pot?R5bMeQH^oBRU) zOO2I<4_f6pP2t}UzkpxBFW?vOS6lfcfjRsa)BoG)|BI8w!e>(i>@TbF{ zULIKOB#We<3;%fdTO$5XJma72|I+@F|4PGVujzZns@VC8qG7=b@95wLZ`OrPe81qk z<=HH*&1%>>J*%xWb!u9JI&C!bVb)poxhz%vYZg9o)+zPx zS#|2HtYhlztRw2&ti#&;5%N0Yn<-=9Z^r*~$}cW#_7>aAwzki$^*(<7^P*Px!@&*D zhT#vxABH~+e;EF7L!~F&SjBg{r&-_8TVL(amR2(U-Po(W^_-ROKq+yb>_&gVckqYd z55pgZKMa2u{xJMu_`~prYqZy|AJi7ika-#hr)I-{J&yU$Zhy(&d|`7@5Br_}tZ3Nz zwcb|v1^fd03-|^6vdx%n2Y!M51^iN52{iT(_!>QYPWbDj{}2D%fw-;T;rGEW;1}=< z_yzm|egVILU%)Tm7vE^F3-~*jTg>@Hul76%|DA~cXX*dw`9GRpvQ4+jmnr;@od3)# z9P&$FqsP1k|6{~|UVwkJJ^#M84PU`9G*7z|{%UQ3jIBH_^E9dp6=Q$lss#9t+v@~> zc7pr~YfH2KzJhf4iGRg!{|Nt+R{f3r(?`I68UNpj{ci_1dS#g0{QR2vC4j!qGuLXHb)lK<3sx&wEbmmSCyMEd`r^pC8&{X_p(;P0@-zhwL;mj0vf zqxUL`F3Rh%ztq219O}R8`p#+TR{8M%X@K$XCF@)(W&BsrzfDf`5BfLE-1>->M|29m z?tuTAbv^tOBmPgk`d{kbFPU@9IRyUn9ojqlnE#rY|C*^|GxL8l^M5n*pZ}OPr-xQF zV_l~U=A-|@-TZ#^zaRbYNB{fL|Nh?kU+Ta8>Y^ZJjI`=*PpMO_1OAZx+Vd6OG`=ph zfeRnOh5zHi|8e2}x$u8n_&+ZEUl;z57ysur{*Tn0YnXfO*~GO?oNp%g;12u({txkg z9>V`|;s3bse_Z%KF8m)C{*Mdo;KKiL9nxOUfxqo*Z81L9o5b4QHvM6Hf$;Bfz%OP6 zDj%2~*p@vn@KttkU`r2w#-4BVHvF^T59@o(XK(MK!J|*2(_95C_4__AkO!%dZOk2_avE4H+;(yYX*k%vyzF)@&3T zwfV)w@QRIZ**@W(1OG2(jQe!K4#t4E%d>6+_RoX=7x?8f_kG*6Wy`i`%gZ(gJ}BFu zm6Wa1R+fFLm6eritINu?^0Lyvnz9eHwR4GOjl}m?E^PF!jPT!q|4KK1V9Ry*d)!Z} zOqs6MR*nBe`&eJAl?B&nA3X%S!gnS7#Ndg;%UJxuX##!$KWi0OyK$6nEo&B7!vVjL zF@5;u8kZy3zkB?&mt$>nZZ`4XC%E86RcKdeHaN;BQNSf2_Q|zYqMa zw)lT@^tn5=rS%T^1^j0G2!0Lz7WnICYuh^JXb^!1kGow9R>M1vcg_)i&h4r&Z)JX5FBz} z+8-4E25&FHdSCd}!W{TlV*g(CiN$O`Hc0+nzQg_CxAQpN9t?l1vJ&JUhW_brtbb1B zkB?OcC&zZGOMMCGpP7A?kqE!c3;wMR`J2%Hefk-F)i3%u{LjN5cA)=%ME~~berEyUA3@&owE^8F9_{=-f9Z^C~Q{+q0SxXJp5i`?U>P1W~z{rg~%S&q|7PqT#{SX#a{d1m`dqJZg!s?9#D6M@)m0MzDQnm^z1KPM)D!*{cKr|k2J5=@ zfzn4dY9H#X|7&IaTPy3|T8YK968~%^HrY!2v-P05Kx55D_j6|J+E}T6#yuVW%h>;< z!5Tp89OHQYF!;0JA4B^eL;HV>_J6H={ZDn_AFXq(6#m=r%k`gkT>kG%g9bG?nd9_XJ5#KB#}gVOlgf9kbu9Cpj~KYkm(xfa5H;yvQ8h>KsH z|E9fev9=riPw$8S2KJv||DAW=M$rCeVgF66|EpsCTa|t|{|NRENBHj;2RuD|7s?PU=HKNH)BdYy|Ep;Kt7!jaw0|%2e?nt=GT3DvspLl+Pn7R}M)>{A0m-U%((*}^ z->3d9?Tq^3cujpi=U=KfhxPx`|2@h0XTAR_?LW@Oe*^nZrv2wI|K*^6#~C&KKQ~Ak zWIq`t%75BFQ-S{)`~rRfKhOVc@Bf}Ime=X?07T*7DVf|+d@Bg;& z{%;G<>V4?HUfRpAzK{<8I_!TP`-iZ9i1r_1{tKc1LiGPNJR=(s(ZBVy{|?%Ji1r^s z|AiR;Ld^esr;Qmbrx2oHIR9j-ltj`|W-64SGF3_x#Y`tD@`Nsh^!JgJ6T6hZC<-}r zDSuYv1!g)#h)j8&BD&I*Nu^xaHC!p_jHIGenbai<4Umy6>nE8ZpIge^k~@`ASBJKV z(oAJ|U`U%#hRc+i3|EHUO-mzbz)FV%hFqPb48Ph(`jc|^_ulDMh3kg?q=?Rvu9BZg zyGlAsZi$~piAlFaXI}28kTL|Ok)uMTL%YWOFBRhMekA?f)lsEGIj={$BeG9AO8%}z zQqD8?yHg?e1Kg2P^FI8?yzfF>fLU;)LFp{veu}nRw@SoFj1ft9l(L_th|d+$PDQMh c=gX9w%(SFOdTXT2w^O;5F3;;yI){?}7evFw0{{R3 literal 0 HcmV?d00001 diff --git a/src/TouchSocket.SourceGenerator.Rpc/logo.png b/src/TouchSocket.SourceGenerator.Rpc/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..d4199b5c36341bdd07f21fcf9a235dd057ea1fdc GIT binary patch literal 11413 zcmYLvcRXC*^Y;p2MO!36u!x9==ux8+62145CA#Q+wXi~>MWPcWghVfkXuCQgYLrDR z;iLDqR#~3w`^WG3U|>?< zpCs>FIN(O^@xs&_1Y)4QzKHrC9?F40?4Xy*3I+k$+jHlB^i!>5d#ztC-O)rl^m!Fg z8ZWL!(qmouQ>hqd5D!w}UIhsDu_re)&9<;FYP=%A9ulTbvB`)+4$|O%_p?Y6hs=`o zd0i$#BW%%c37~-7y4CyfZn)o$DzzuSPioaT)olZxenQQh4We{<7~kR~ty}0g5k5}Q zU-XuC^=h;pr%4i=@_Q1K1uutNDxBd1yB}xHOR@HIHE#;ezyEc^=KhGZFnVXmWc^Te z<%(McYzXF<(nvbOYzd z#Sh|6e#-XzYUa9RteZ;3S*tWTZmaxmGFFDWB5~D@=XzmR!OaN=yZYX_yfnQvtafMH ztO&cJ#4d(8*@t_R+8)vbajT2uX!tuw=EG#Sq%WB&OkwB}cMP9AM%uA;@<{jecz!8Qngs6=5coV&1 z?w63gCt$V6MRGaO^5;prpfk^(7Y055oI}GdO1vC3l5GhWEhU1A51H~)Q-hCfL(P1% zZ}2T;=WK5Nk_rqaoTy*Ss^NGzA}75x=1?XT6isp7Cw=uzmf;IN3z&1;mh@$7m?3#T z*zJp41r|yNQ_acEUFDk#e3@|kJvMI`q8P9ZA3@I@{QabSevkao5}uoRF;Cnsp3d-< zReD(RLxdI0#S4sxR9f6Df7r3iqkU4P)PB>Nqyt1~dcNImq}*Eh*`slT1{UMp!pO6w zUSuA34GF=CL7`IZLW*uDTWg$Si@>2ASfH8Aez{hCsyf#rPQi40^^@o9xik4$`6p?V znYw?Xt5TYJJNp)4l(mO!LRlwKlv_9B_j&_cMr02CN|%fQ`<8-K?@HLh{6pn!b1PoC zG~|3Vs#2%_CG@DfS+)LV5R~km5+*Y4wX@_5b_%8F^y0u<#)Ti%EuRHUeGE)pOZ{$$ zHo(|c8qOP=tlesVIhYUc93p+Ma1IcN34gip(;Mo0fi?6$y7XX~=W1^MrobE}$69xEs!X3sQB}h%L1)rPhK-9^X=H$i5B@R!sf^(*_+qJ; zc*=I+$}PG5;N2>Mf(=9(A@gFX`*hcqs_2ByaC9h?%b_lC%`Su1_d{;<&oD=3MJq)x z{3E$LPvUtC+EPWm+0yQgoR&l-<0?hV8dK-4Z6Jb2Ur*h`iV{t5%{BS zLxbo^t2|yjX|tspeP!h2I-?ZBchVCP+%fYdGX zAG(H#X$Z0B57jm<$+KDR-syn0v1z$XqXhcLNL%XB0SnD+trj0|N=H(Soukptg2rZgTtYqZwy0i-=8IhO<7uI*du!4 z7Jm2GLf_^hS^EU`XhzG7BL_*Z&MNQ29*7)o_-PlF;IfkKvST+Ivq#Yl%X#9CgebX3 zm(M3JhuEpL?@`vmms+qPJP(Fl?)!>h&RS`YN}>xsy!W);7+JmIeeSQn-f^k7Z}GeL z?r^#om3-wt>4Le3cJt4(|ZA9kApB^G_70o9#g1y&cwB#;vxG=SR zs~zXxz&5_SeodL}!f`b!C%=qb@ZfV0z~1@q=3LI_fFJVn(h|3==itrAwRR8}A_Sz< zv#*-0CHqg=9JyegPzb@v;zRC>FnxXgNbJuTWgSs)ExS#1Ic)-_s zxy#T5&KI(&NNxjrHtMBNj(k?p1H*H(wO{x2#HQgvpUU%t!_UOiUJUz=U3DtXNRavt zdtPTS*tj6|OJz1&|rW;rEQgg|hYdT|VXjKp%@nv%DF1%+G{L@~l< z$o~%J7|Sv*zVb>4do=RfLYRMhf1_D{W8>rN$JUONqHwk^+Sz8JH^Lq()5H!p;cH9# z^IzbMMkBDNWIyZso_lEx9h-diM+UC7x+3%J*g(jw5I@=dyEGU1LdW{u>BF;|jVd!y zi7bOaY*(#U|H`#CCmr@hWr4Q_xd+UnDdtE#n>5cSGX}k;grgbwam$yz$qfcb$HFuh zp(CmI^F3r#ZcFLJ*qs5XO7hT8>631b*>Xia-Nh?n%umX;BfqT|%py#K|8nXbwR{%Z z3N%K?%FfHlr(CMe{4x>fXEgs@OR?UFn$()vX*Av_Ityy33DKwA$bw;emo>iO>v=5) zFAWwuYN`Vw*;Ixf4n23n(pPm40#Bly^qr(Z8wD2&1fRI?d|Y*Vs9ZNRE#29iz4 z4A+k~CkGm`W)FECcP*^{;v};#&$+Brnl6(Krm&m1Zm%zCqHvU@>gmakYSvO|mI1%y z^#=cOR+@u9c^%M^V>1@uF8%V)oVND;9C&zm^z z9C`L6(kNsP_#^Ak7V`1S9`k1(P|h8J`Mjk_kVnMbws)7R6tRXfUS`h}nx9Th)&6TM zL6LoPD}dWgkn8`_8sXPudvBYnp^#@s^C~gzbNF^;FtccEBu%TsMG)sSB7R z%jX)lj8{JGQ!#*qoR0_W$yGa2W!M@%q2LdE{@i~-MW0WENvqg&-~IbBeqQH6#YEz~ zObwNcI|)LVI$SgA%gly;xyFQ$vv-gBGdA$oe+7E*U8-K%qX@v^Na$duZM7!;z3ywR zCvCGB^Q*j_F&VfVvevsx)7!jDGs{LxxgA|a=F#W)uh;c=ZHN0anY68SKZ)p8N*NQQ zICn|u|3)*@!ri$YEAPx3fb&~=m~0VlqS_4Qhi<0HM!wJgoaA}2mQELWHD6k9BaBb| z%)FcT&k+W5y;48su*zxR{0%A2>DqocBc3SXI1D|a3EqB)SZ~!%uXk(r0s>U&l>U6= zSV^6|zzDe+Dm-3|{7VafK<=_9#jV1^%JKGTLg>R+TxERuyjB?VUGEFPrX0V?=K+C& zS2@L@`!@Sl+A6gTN!gY()%g{F&YBIvY_cSof9v#W8L;1Pc7ax8Xg;3bTf-Vo$IqrD zC^uI;pJKaL?vDTbqI)Q@*-(}>HFd#flm$)Q&dEQXN(-y}bzF$sWt5XExN^wQt&wOp z#y)Q%QeO1MI56cGKc0HQgbNPS&Q;I8IhBixT zMI=%8Z(xa%O)CD>bIdfCdcl|7C$^U8V6I7eVyAwKiEjse|1-s0`R^mdTC$SP{96$) zv>(6c{Qkm zmsx!Rp`j=-&wjdrKFoP@6ElF75XMot6&)(>6X!#R+r+s-`Txxa4RF^C9nvF0qUcu4 zlQ2x8Q-q2jOVJ`XoYzf3CZBtiOWm>EC$pJC;PVv(dGcF#q^RmJMHTOTObOZLjT_dA z4&&K2zwh5$R-q6on)~TpjklVWLgeMPE|8+E`d+rIe76qRe4#n?HA>*Kh;wLPx|<@- zDXZ1z(q_N4UV|vUiUHF$^^GzD#Urv8^{nB>@zD3vbkDD>8}SxTF2$BkJQXk$&I>MY zWDjF?<*2jPl*40oS&u2ax2VjH1}$3*q*ph^4H2zB5!+`x>Fxiyk{=eu^3k``SG(b7 zJb<}Wv1vRNw77_ub0cQo&A*1SSjf*=3968j)dj5v2l8=l zbw{F>cKVPDss;;nTL}WaR4^LY+bRZ{4lFA|rj1nRjE+VtlY#_B1A-6%=qwy8k0Ayr zgF2uf_8Wlr0nvt6k%3}>fDDo+0U|5t{sMQvCyouh!>g_Ph!Vs|xptkcLOiG9FMT6l zk4bzBSJW37Kppn%?>f_RedeSZZ6}6?04J1GL?)yAMho+eFA8%7j{OoTXcH|*C@!Dk z?0|md2UgmnrBO^7Q7sz(6yPoIR)3ET5C_!wrdq#W0T8Lr{f{2?^+;$|gxRUKYoWr^fcd?B{cOV#x> zcs*BBT{4}S?7n-`Nu!VR<*$->L&B-pddCpd+&c+G5}xMukeOf#ppd)xXTlQHkQ&$^lpFzy*NVr7m2i(Mdo1Ro|2&{?l0*<{J8HM+2%+8{cV|5C0zzVNJJr3m4bIA)%KOTSRToLTJ=31~&{xvZUhacoEjC9`!X~ zNg(1`gdV$5C{;>UkpYU46%h^}>O(>dKc^A~qL?D6Mp zHjT`XP@cYXA8~NmAY=q})O;V>cp!4sV1=?kQ*kEKeC>y7TeOe3g2ES^_~3k7S4J%F zX=Msq*FJT-C@W2UaDOaJb{Vxu=A_u?OW; z{Q0Ft6aR7^#O{T(*bvm8=LX9;rd5@FB3%$Y>Upcv{v-hu@07xfXbljY`uPkD-+vY4 z?f<_$dQ&8%%;63fxiRF)Vmn#Yvm9~!yV^usFkDDeg#h{)Ud8acw_kn0@#oLQUYAA+ zn7~7lG!b6!5E+>3^Rr{A^n>+KW`)k~jBonyX|j=9cbI1#A=fU!B!+1T+J@r$H61m= zT07n93B^5U+iBwCHEb;i{bfDC=(ra5r&?-Gtp49^M5}yU-ih-A@A0??t7@=|k1PjO zTtn)Q$td2Kc>DziwWNMAl}y36t-E0S2C!2%d)rat@pM?0@};-h0DKrhK6E(gIVC^O zzdZluMppi_=OpDr!#8Ps!r2|GfgOpUIVkD^fri#&=Af|o^jXOei@J0@YrZb_nCsROjWmP7U> zAK%*k%HGTiFaBWB;L+A{Y@5sUmy7i-YZeDGj;>$3J_UC3U5#DSM^Rr1XVbgM4Xk0$ zwL+rC;uBTQ*!VwoB$WB}c%^QWr(68V2dOXk+Sv>*)|2mwOxz%7irZIV6T3nD>g0>7P95ABt)dEn zlrLyC;Jt*O)IPVdLKyzwbKD;z8HE89LC^Z&b2T4Y@<1OQS4@VU2y*O-3*$SPgv6Z2 zt1X8NoIp1Qmm+h2P{s6)*(xWY!pqR;&Xba|2~9 zWHh%%ZlE`mKE3hEW?X-C<;Y^Lb`UiO4i+#VYi)F6=A1~=ypS?NX~d1QBbMb1LJd!X zv-RZ?b=8`XZ_-0^Q;LnQ2t6mN;PP2ijWzP$cFMWXZsgS8J>$_~Y>_3xrH`o4c+GAsXvg9lX~BKEH_Wf0RR(6)}SzCG; z^$>+oGV%r4BO@%{g@mr$MCg^HIuzp!3|?mxui$EY@4SysBVFspKU zDjqFw?xD_J_od&i{`(!k3Xbg7>%O*77y~RfH;{<$%>GmDglI4WOdEMm_C}Zz_e7RZ z39G~8wDj*^_OQe}Km;^$GB`o-({}uRP3|2X{H`-C@rAMgvyV)~SJ^}-zH?r#Re6z4u$9;Xh+N;5L!h;(z0P*aOJY#Q1u@=L9A zr#8ht`yyP+zcj+i$B5CtNPKV|D1IKr+qjupGgfRxhivYhM{DFAsP?4?&xboM`?wQ( z!4s3pTdxh>?;}DYt4_GqhQBu=QT$wUO>X2cZ-*I1+(pNXRDQ5lV)by!TX}~5oiNO6 zXD37}VE@C9hhy&^%^D^vFu1 zm5D=^gfK6YaXIcVWo@`idhb@0OwLhf^ev7^Xr?zSE;X-r<}>a;fXni0SFKNO_R@RA z+vgUT__mXnH3c^MS8Rx-$6L`?hn@@(*rbcOwARW|bm`?6^mj7CoUisxR36n0wB2dh zf%>TVk)>Gu`+E~_24ti28V1wy#3@gG(4n+8VHC|W>(Ok_Pqn*gf+DKie|utR!Y)jb z%0!t8zcF1!o*P@F>sLTgQ;w1Lm2n%~aeB(!?>4TJ?NGP+xU^VazlAFnN@4Szi2+KqGz2dIBQ3*)oF$2HkZdgeDDx?nf>`6A+gHc zb<_#7B;WLka-LM-D9l>1pqrHmdllfuoZfd4JmG{X5dDu@i&25GZ;$T|)mV@jgDp@} z1i>QQM~{&_)3i7c|4y{qW|}(Kj;FmV6PiDp3zAA zJ|$l7Y84A464UvH^DF>pS0r{(c`B3?NNvXgyafqNt@+=$(>IhEBb^fmy#0x}KLA=m z!b;@Djn6mv08sjosRJcB5kvt@FGSD{75z^}`BGHlxA(ujODD~*`SBt`ykqMcfRsUA z>Id_;r)m<+Ky5_+QJx`Ms19cYWG^qce3h~&93aDH`Y!avIZ6NwE==pu|C!$efCh{b zDAjW$|2g2?Zwp_Gn|o2E&1<` z0fR}yJ_z&T3WAst;fNljG*v@55fAn*-h6i=hQI`>X;Q4q)yBt6&nzTA(!Y|Ew{o0t zr-rc^u{}mF5@j-6{NsZSc{+BtO_})*(6V%CYKqN*U~D(o9v8IucYM#|V!c!-46a}? zsjKFb7qOKP&N9o8IJWph4UwaDkjuXV&^3xUyNxlLGKyT@w41<7NuD+ehhxP@KE16} zw{)DC9YY#wLva5Nl0L0)#5PF)k>(iZig`u@XdjZQTPm06;Hcj+u>6h>4rnNbvMvZN z#_A0;7C;sJIn8l3Whj5W~8LS z{Tg`z&yJ+1(NvZ$7K#5+^ApcI5`Pzj<%HC$NnB^Y5lo$miwPL#3HobxHVavFxrCUhtB|K0unlaP!(6X1}2(NVW5W zml8^sR(!sd+)?bin+pXY*WxmlI)DE`=+tOE;+T=6M<=9DEz9aA{EH{mx+5cPBl-G0 zuSW&8&m($FGqbRz5EI~XXn(u8?QZg zkt84@!Pr=^N;RebQi5*@4>jXJju%BI;{wk|9&II5-kaBJ&q$rW`jKTOJ`gLhQ_<*_ zCrJhGoeKf6eT?XEnQlzA8UO~rKzGSbiriY)FS^Qp>0-274iBFrV^}&VLv1=FDI8K| z4MRtrPu060IPf{~sQ*3cY5#fyx9niG<4Jf)dC9Z2V|s)~*kbB#KmC#Qjpgi5!)vF- zu7p(79ZBl*_x_Mgng;DxjC!E{`{QVZ<2&{kq0=XXE~6!_3WdZ}TO!Yr2lXGwBC$=>mooJhu0yAEM;IxxhTNFkb+y)0KW|M_hrgK<<*gb5M1{-I& zrCEAuYqK(pTp^voJ0Av3?p-p%dISWQ9s(ewY$E{xA@&ygVV< zo;>@E~zUc#J7- zSTj`XGjeWu3&HV45$?eXXG`g*_j!TsD)l>WHL?gv!-)u)^W*Ob4PKnW)@_il)RKi8 zZJ`axgIHb+2bh(L15T(dh0uTuJ&FYf4cl>tZd;!A{O2PJRIzGyafw17c2Yw3z8Pu* zF#=SKo4eFikPDiRJ01O>|M0NceeZI8!C$x- zMByNe&Ow5h$>Z6#P9F#cEytS3^RHW|l)UpF#zBGJ)i@DK2n!(&bnJd}PD7wKN zHe5N7tKJeDxWO@w(@4c5+$H-rnho!7g^-`8nD_eohzE?LK33c3QspJ?_T^3_LU0hZ z7E!cAP1n4!|410Bd?u4eFN*MOaoS{iYCuephfL97*x>ZR7LRoEn-sKfu&R05o8)bh za=L|il|&M7JZfEUN?)btk)kZvMd2ybj^do3c^1@0dRAOFDb3bad$X4Zk}>Npy*Y3p z&fK2&I6P)8Ym)SZ9gk2NRTSv9JNn=5i)nko@3+`*oY^Bo4_m|%^Js?5nzj4Q05k%z z2@x^#?|-5urpVZQ*i-wKY7B@L2pzAYLYK!6B`yu?my9z2=? zbB!Ftlfwi)p2SY!E#%A+IqegA3JRr58iHBbxJ*Q4b_wP2UHQP7;YDLRTr$b3T5*L<%0@Fy3=1V9ds2clPn zu?=0h&T=WMSGqYH^d#%~6|pc~x2ir3)LGf>)o+0HOOma!9p015wGWr(lMDF3a6>{= z7C4c>vC>*i%;`u3${x^et+6Z-5~+y_`DmSHbmL+c#Gb%qJCbKmcN6UUa+;XkJ`$mz{hAV(K+zHJ^FjPAuVX;mCuS?y>@?S-smwMC{Gf4l)sk!R>6=x`RKw`T;yS#ZDHgZvB@!! zw#K}B5G|J~)s zqhx{96bib}Pp1IjQ4j>SB(m;EBBLM&2gQ6J&F~2z)tG*pDg#m;T+?Xc_S)13ni(M7 z{6ST@&pSz>dLrV0KTnbfq1XC1O`L^1U2{MyDBR1%K+iM7~c0Da;p@ z5##HGphJ1n)B9w3Ehpv;>2;bzQ7)U9=S~SAS6Ex~zsG+Bx~mQB=z$(Z_?DJ78WZXE zGYjbCgqH<`ggTye|NP+K;e9te`iGwl&p9*|7ApkXCfwGU1X zhy{6%%~TzMQ}dnUKFlnVC*>-!xGu@O5e5fd<=M@v*!KUjTjF(o5L`i-w@QNXe1C#e z7&)f^sFwuRlEBhhWi%97{|a7-=%baHU?O{W{U#{2@h!f)387u$J9L}7#av!<-my+TRe>>TfAzyc%}|ObEdRN;!bq+ z+i`hdM%`f$bA=raiXQn&M!%~jDHZadLW8Y4`0#!k`Aj&0!!zPUdBmta3>^^P@S*v^ z3}M2hU*V__#0x#Jy*|ySX(b4TzrEn`WN9a_8B@H(3Tm}{xCMN>@)5;LSw*V=z(05> zx&LBQ=^MBKqj_`kA;=nruxEr>#_22#>vyDwW-v_&j=?M{EQY~@b8B-^;pEi2mY|6QeRvGAGh}x<-KI^^hp`6b=KqC5LHumK6u&e|kN3=!}qtyIO1`ofLQ&+z* z=Nw2O`wR{V`Ohx8D%x+ehn4~RNvL7;zrXDgD$Vam09%L|{je%hV-K{p@AeA<`$gHj z@y?Y8xEwF21pFBOpc^|Z!=lV5`xvm;(JGr{C$Fg6{ZDlfz~Q$_ueM=o_Jsm!pufZ4 zLRxu$A^$GW_X*WkY11BJm8XINM-z$r9DY3-{_cG)^!3gb0CZv!hgEAGk=Tjo^U>#Y z*#JR|T{qoUY%P4$i_9HJog+F2ga!=%VH1s>;eqpb+dYwdwABSe1A?VJwyRgEt7jwn zq%#!P1KLk=ocG;77|fW6+{iY;xr|bt0HuE9xB?gqcPvHYc8slcciA2wURzvRPDD0t x8OKlJR2ru0ThijgGJzCed`tm~_;^Kj_53cELmYn$aLyR?^0}6Bh2pD-{|Cz~j=%r_ literal 0 HcmV?d00001 diff --git a/src/TouchSocket.WebApi/Attribute/WebApiAttribute.cs b/src/TouchSocket.WebApi/Attribute/WebApiAttribute.cs index 9930da67d..70a0e235d 100644 --- a/src/TouchSocket.WebApi/Attribute/WebApiAttribute.cs +++ b/src/TouchSocket.WebApi/Attribute/WebApiAttribute.cs @@ -13,7 +13,6 @@ using System; using System.Collections.Generic; using System.Text; -using TouchSocket.Http; using TouchSocket.Rpc; namespace TouchSocket.WebApi @@ -24,7 +23,6 @@ namespace TouchSocket.WebApi [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class WebApiAttribute : RpcAttribute { - /// /// 构造函数。 /// @@ -34,20 +32,20 @@ namespace TouchSocket.WebApi this.Method = method; } + /// + /// 函数类型。 + /// + public HttpMethodType Method { get; private set; } + /// /// /// /// public override Type[] GetGenericConstraintTypes() { - return new Type[] { typeof(IWebApiClient) }; + return new Type[] { typeof(IWebApiClientBase) }; } - /// - /// 函数类型。 - /// - public HttpMethodType Method { get; private set; } - /// /// /// diff --git a/src/TouchSocket.WebApi/Components/WebApiClient.cs b/src/TouchSocket.WebApi/Components/WebApiClient.cs index 071a570b9..40e06c603 100644 --- a/src/TouchSocket.WebApi/Components/WebApiClient.cs +++ b/src/TouchSocket.WebApi/Components/WebApiClient.cs @@ -39,9 +39,9 @@ namespace TouchSocket.WebApi #region RPC调用 /// - public object Invoke(Type returnType, string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + public object Invoke(Type returnType, string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) { - var strs = method.Split(':'); + var strs = invokeKey.Split(':'); if (strs.Length != 2) { throw new RpcException("不是有效的url请求。"); @@ -79,18 +79,22 @@ namespace TouchSocket.WebApi break; } + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); + var response = this.RequestContent(request, false, invokeOption.Timeout, invokeOption.Token); + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) { return default; } - if (response.StatusCode == "200") + if (response.StatusCode == 200) { return this.StringConverter.ConvertFrom(response.GetBody(), returnType); } - else if (response.StatusCode == "422") + else if (response.StatusCode == 422) { throw new RpcException(response.GetBody().FromJson().Message); } @@ -101,9 +105,9 @@ namespace TouchSocket.WebApi } /// - public void Invoke(string method, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + public void Invoke(string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) { - var strs = method.Split(':'); + var strs = invokeKey.Split(':'); if (strs.Length != 2) { throw new RpcException("不是有效的url请求。"); @@ -140,17 +144,21 @@ namespace TouchSocket.WebApi default: break; } + + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); var response = this.RequestContent(request, false, invokeOption.Timeout, invokeOption.Token); + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) { return; } - if (response.StatusCode == "200") + if (response.StatusCode == 200) { return; } - else if (response.StatusCode == "422") + else if (response.StatusCode == 422) { throw new RpcException(response.GetBody().FromJson().Message); } @@ -161,32 +169,32 @@ namespace TouchSocket.WebApi } /// - public void Invoke(string method, IInvokeOption invokeOption, params object[] parameters) + public void Invoke(string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - this.Invoke(method, invokeOption, ref parameters, null); + this.Invoke(invokeKey, invokeOption, ref parameters, null); } /// - public object Invoke(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + public object Invoke(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) { - return this.Invoke(returnType, method, invokeOption, ref parameters, null); + return this.Invoke(returnType, invokeKey, invokeOption, ref parameters, null); } /// - public Task InvokeAsync(string method, IInvokeOption invokeOption, params object[] parameters) + public Task InvokeAsync(string invokeKey, IInvokeOption invokeOption, params object[] parameters) { return Task.Run(() => { - this.Invoke(method, invokeOption, parameters); + this.Invoke(invokeKey, invokeOption, parameters); }); } /// - public Task InvokeAsync(Type returnType, string method, IInvokeOption invokeOption, params object[] parameters) + public Task InvokeAsync(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) { return Task.Run(() => { - return this.Invoke(returnType, method, invokeOption, parameters); + return this.Invoke(returnType, invokeKey, invokeOption, parameters); }); } diff --git a/src/TouchSocket.WebApi/Components/WebApiClientSlim.cs b/src/TouchSocket.WebApi/Components/WebApiClientSlim.cs new file mode 100644 index 000000000..10170d834 --- /dev/null +++ b/src/TouchSocket.WebApi/Components/WebApiClientSlim.cs @@ -0,0 +1,328 @@ +#if !NET45 +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using TouchSocket.Core; +using TouchSocket.Rpc; +using TouchSocket.Sockets; + +namespace TouchSocket.WebApi +{ + /// + /// 使用为基础的WebApi客户端。 + /// + public class WebApiClientSlim : TouchSocket.Http.HttpClientSlim, IWebApiClientBase + { + /// + /// 使用为基础的WebApi客户端。 + /// + /// + public WebApiClientSlim(HttpClient httpClient = default):base(httpClient) + { + this.StringConverter = new StringConverter(); + } + + /// + /// 字符串转化器 + /// + public StringConverter StringConverter { get; } + + /// + public object Invoke(Type returnType, string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var strs = invokeKey.Split(':'); + if (strs.Length != 2) + { + throw new RpcException("不是有效的url请求。"); + } + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + var request = new HttpRequestMessage(); + + switch (strs[0]) + { + case "GET": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Get; + break; + } + case "POST": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Post; + + if (parameters.Length > 0) + { + request.Content = new ByteArrayContent(parameters[parameters.Length - 1].ToJson().ToUTF8Bytes()); + } + break; + } + default: + break; + } + + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); + + using (var tokenSource = new CancellationTokenSource(invokeOption.Timeout)) + { + if (invokeOption.Token.CanBeCanceled) + { + invokeOption.Token.Register(tokenSource.Cancel); + } + var response = this.HttpClient.SendAsync(request, tokenSource.Token).GetAwaiter().GetResult(); + + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) + { + return default; + } + + if (response.IsSuccessStatusCode) + { + return this.StringConverter.ConvertFrom(response.Content.ReadAsStringAsync().GetAwaiter().GetResult(), returnType); + } + else if ((int)response.StatusCode == 422) + { + throw new RpcException(response.Content.ReadAsStringAsync().GetAwaiter().GetResult().FromJson().Message); + } + else + { + throw new RpcException(response.ReasonPhrase); + } + } + } + + /// + public void Invoke(string invokeKey, IInvokeOption invokeOption, ref object[] parameters, Type[] types) + { + var strs = invokeKey.Split(':'); + if (strs.Length != 2) + { + throw new RpcException("不是有效的url请求。"); + } + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + var request = new HttpRequestMessage(); + + switch (strs[0]) + { + case "GET": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Get; + break; + } + case "POST": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Post; + + if (parameters.Length > 0) + { + request.Content = new ByteArrayContent(parameters[parameters.Length - 1].ToJson().ToUTF8Bytes()); + } + break; + } + default: + break; + } + + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); + + using (var tokenSource = new CancellationTokenSource(invokeOption.Timeout)) + { + if (invokeOption.Token.CanBeCanceled) + { + invokeOption.Token.Register(tokenSource.Cancel); + } + var response = this.HttpClient.SendAsync(request, tokenSource.Token).GetAwaiter().GetResult(); + + this.PluginsManager.Raise(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) + { + return; + } + + if (response.IsSuccessStatusCode) + { + return; + } + else if ((int)response.StatusCode == 422) + { + throw new RpcException(response.Content.ReadAsStringAsync().GetAwaiter().GetResult().FromJson().Message); + } + else + { + throw new RpcException(response.ReasonPhrase); + } + } + } + + /// + public void Invoke(string invokeKey, IInvokeOption invokeOption, params object[] parameters) + { + this.Invoke(invokeKey, invokeOption, ref parameters, null); + } + + /// + public object Invoke(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) + { + return this.Invoke(returnType, invokeKey, invokeOption, ref parameters, null); + } + + /// + public async Task InvokeAsync(string invokeKey, IInvokeOption invokeOption, params object[] parameters) + { + var strs = invokeKey.Split(':'); + if (strs.Length != 2) + { + throw new RpcException("不是有效的url请求。"); + } + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + var request = new HttpRequestMessage(); + + switch (strs[0]) + { + case "GET": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Get; + break; + } + case "POST": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Post; + + if (parameters.Length > 0) + { + request.Content = new ByteArrayContent(parameters[parameters.Length - 1].ToJson().ToUTF8Bytes()); + } + break; + } + default: + break; + } + + await this.PluginsManager.RaiseAsync(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); + + using (var tokenSource = new CancellationTokenSource(invokeOption.Timeout)) + { + if (invokeOption.Token.CanBeCanceled) + { + invokeOption.Token.Register(tokenSource.Cancel); + } + var response = await this.HttpClient.SendAsync(request, tokenSource.Token); + + await this.PluginsManager.RaiseAsync(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) + { + return; + } + + if (response.IsSuccessStatusCode) + { + return; + } + else if ((int)response.StatusCode == 422) + { + throw new RpcException((await response.Content.ReadAsStringAsync()).FromJson().Message); + } + else + { + throw new RpcException(response.ReasonPhrase); + } + } + } + + /// + public async Task InvokeAsync(Type returnType, string invokeKey, IInvokeOption invokeOption, params object[] parameters) + { + var strs = invokeKey.Split(':'); + if (strs.Length != 2) + { + throw new RpcException("不是有效的url请求。"); + } + if (invokeOption == default) + { + invokeOption = InvokeOption.WaitInvoke; + } + + var request = new HttpRequestMessage(); + + switch (strs[0]) + { + case "GET": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Get; + break; + } + case "POST": + { + request.RequestUri = new Uri(this.HttpClient.BaseAddress, strs[1].Format(parameters)); + request.Method = HttpMethod.Post; + + if (parameters.Length > 0) + { + request.Content = new ByteArrayContent(parameters[parameters.Length - 1].ToJson().ToUTF8Bytes()); + } + break; + } + default: + break; + } + + await this.PluginsManager.RaiseAsync(nameof(IWebApiPlugin.OnRequest), this, new WebApiEventArgs(request, default)); + + using (var tokenSource = new CancellationTokenSource(invokeOption.Timeout)) + { + if (invokeOption.Token.CanBeCanceled) + { + invokeOption.Token.Register(tokenSource.Cancel); + } + var response = await this.HttpClient.SendAsync(request, tokenSource.Token); + + await this.PluginsManager.RaiseAsync(nameof(IWebApiPlugin.OnResponse), this, new WebApiEventArgs(request, response)); + + if (invokeOption.FeedbackType != FeedbackType.WaitInvoke) + { + return default; + } + + if (response.IsSuccessStatusCode) + { + return this.StringConverter.ConvertFrom(await response.Content.ReadAsStringAsync(), returnType); + } + else if ((int)response.StatusCode == 422) + { + throw new RpcException((await response.Content.ReadAsStringAsync()).FromJson().Message); + } + else + { + throw new RpcException(response.ReasonPhrase); + } + } + } + } +} + +#endif \ No newline at end of file diff --git a/src/TouchSocket.WebApi/EventArgs/WebApiEventArgs.cs b/src/TouchSocket.WebApi/EventArgs/WebApiEventArgs.cs new file mode 100644 index 000000000..6587c6844 --- /dev/null +++ b/src/TouchSocket.WebApi/EventArgs/WebApiEventArgs.cs @@ -0,0 +1,66 @@ +using TouchSocket.Core; +using TouchSocket.Http; + +namespace TouchSocket.WebApi +{ + /// + /// WebApiEventArgs + /// + public partial class WebApiEventArgs : PluginEventArgs + { + /// + /// WebApiEventArgs + /// + /// + /// + public WebApiEventArgs(HttpRequest request, HttpResponse response) + { + this.Request = request; + this.Response = response; + this.IsHttpMessage = false; + } + + /// + /// 是否以HttpMessage请求 + /// + public bool IsHttpMessage { get; set; } + + /// + /// Http请求 + /// + public HttpRequest Request { get; } + + /// + /// Http响应 + /// + public HttpResponse Response { get; } + } + +#if !NET45 + public partial class WebApiEventArgs + { + /// + /// Http请求 + /// + public System.Net.Http.HttpRequestMessage RequestMessage { get; } + + /// + /// WebApiEventArgs + /// + /// + /// + public WebApiEventArgs(System.Net.Http.HttpRequestMessage requestMessage, System.Net.Http.HttpResponseMessage responseMessage) + { + this.RequestMessage = requestMessage; + this.ResponseMessage = responseMessage; + this.IsHttpMessage = true; + } + + /// + /// Http响应 + /// + public System.Net.Http.HttpResponseMessage ResponseMessage { get; } + } +#endif + +} diff --git a/src/TouchSocket.WebApi/Interface/IWebApiClient.cs b/src/TouchSocket.WebApi/Interface/IWebApiClient.cs index 0d039fa89..157eb8bea 100644 --- a/src/TouchSocket.WebApi/Interface/IWebApiClient.cs +++ b/src/TouchSocket.WebApi/Interface/IWebApiClient.cs @@ -12,14 +12,13 @@ //------------------------------------------------------------------------------ using TouchSocket.Http; -using TouchSocket.Rpc; namespace TouchSocket.WebApi { /// /// IWebApiClient /// - public interface IWebApiClient : IRpcClient, IHttpClient + public interface IWebApiClient : IWebApiClientBase, IHttpClient { } } \ No newline at end of file diff --git a/src/TouchSocket.WebApi/Interface/IWebApiClientBase.cs b/src/TouchSocket.WebApi/Interface/IWebApiClientBase.cs new file mode 100644 index 000000000..b413ea8e6 --- /dev/null +++ b/src/TouchSocket.WebApi/Interface/IWebApiClientBase.cs @@ -0,0 +1,11 @@ +using TouchSocket.Rpc; + +namespace TouchSocket.WebApi +{ + /// + /// IWebApiClientBase + /// + public interface IWebApiClientBase : IRpcClient + { + } +} diff --git a/src/TouchSocket.WebApi/Plugins/Interfaces/IWebApiPlugin.cs b/src/TouchSocket.WebApi/Plugins/Interfaces/IWebApiPlugin.cs new file mode 100644 index 000000000..96db16378 --- /dev/null +++ b/src/TouchSocket.WebApi/Plugins/Interfaces/IWebApiPlugin.cs @@ -0,0 +1,35 @@ +using System.Threading.Tasks; +using TouchSocket.Core; + +namespace TouchSocket.WebApi +{ + /// + /// IWebApiPlugin + /// + public interface IWebApiPlugin : IPlugin where TClient : IWebApiClientBase + { + /// + /// 在请求之前 + /// + /// + /// + /// + Task OnRequest(TClient client, WebApiEventArgs e); + + /// + /// 在收到响应之后 + /// + /// + /// + /// + Task OnResponse(TClient client, WebApiEventArgs e); + } + + /// + /// IWebApiPlugin + /// + public interface IWebApiPlugin : IWebApiPlugin + { + + } +} diff --git a/src/TouchSocket.WebApi/Plugins/WebApiParserPlugin.cs b/src/TouchSocket.WebApi/Plugins/WebApiParserPlugin.cs index 64a338913..719c34207 100644 --- a/src/TouchSocket.WebApi/Plugins/WebApiParserPlugin.cs +++ b/src/TouchSocket.WebApi/Plugins/WebApiParserPlugin.cs @@ -23,6 +23,7 @@ namespace TouchSocket.WebApi /// /// WebApi解析器 /// + [PluginOption(Singleton = true, NotRegister = false)] public class WebApiParserPlugin : PluginBase, IRpcParser, IHttpGetPlugin, IHttpPostPlugin { /// @@ -144,20 +145,20 @@ namespace TouchSocket.WebApi case InvokeStatus.UnFound: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("404"); + httpResponse.FromJson(jsonString).SetStatus(404); break; } case InvokeStatus.UnEnable: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("405"); + httpResponse.FromJson(jsonString).SetStatus(405); break; } case InvokeStatus.InvocationException: case InvokeStatus.Exception: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("422"); + httpResponse.FromJson(jsonString).SetStatus(422); break; } } @@ -273,20 +274,20 @@ namespace TouchSocket.WebApi case InvokeStatus.UnFound: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("404", invokeResult.Status.ToString()); + httpResponse.FromJson(jsonString).SetStatus(404, invokeResult.Status.ToString()); break; } case InvokeStatus.UnEnable: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("405", invokeResult.Status.ToString()); + httpResponse.FromJson(jsonString).SetStatus(405, invokeResult.Status.ToString()); break; } case InvokeStatus.InvocationException: case InvokeStatus.Exception: { var jsonString = this.Converter.ConvertTo(new ActionResult() { Status = invokeResult.Status, Message = invokeResult.Message }); - httpResponse.FromJson(jsonString).SetStatus("422", invokeResult.Status.ToString()); + httpResponse.FromJson(jsonString).SetStatus(422, invokeResult.Status.ToString()); break; } } diff --git a/src/TouchSocket.WebApi/Resources/TouchSocketWebApiResource.cs b/src/TouchSocket.WebApi/Resources/TouchSocketWebApiResource.cs index 6a8b9831c..02198c6d0 100644 --- a/src/TouchSocket.WebApi/Resources/TouchSocketWebApiResource.cs +++ b/src/TouchSocket.WebApi/Resources/TouchSocketWebApiResource.cs @@ -11,8 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.ComponentModel; - namespace TouchSocket.Resources { /// @@ -20,6 +18,6 @@ namespace TouchSocket.Resources /// public enum TouchSocketWebApiResource : byte { - + } } \ No newline at end of file diff --git a/src/TouchSocket.WebApi/TouchSocket.WebApi.csproj b/src/TouchSocket.WebApi/TouchSocket.WebApi.csproj index d0c08620b..6fc5d6b5a 100644 --- a/src/TouchSocket.WebApi/TouchSocket.WebApi.csproj +++ b/src/TouchSocket.WebApi/TouchSocket.WebApi.csproj @@ -1,54 +1,22 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 WebApi 这是TouchSocket适配WebApi的扩展包。 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt TouchSocket.WebApi - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.WebApi + ..\..\Build\NugetPackages\TouchSocket.WebApi - - True - - - - True - - - - - - - - - - - - + + + True + Embedded + True + diff --git a/src/TouchSocket.XmlRpc/Components/XmlRpcClient.cs b/src/TouchSocket.XmlRpc/Components/XmlRpcClient.cs index 5fe31b5f4..c93cd907b 100644 --- a/src/TouchSocket.XmlRpc/Components/XmlRpcClient.cs +++ b/src/TouchSocket.XmlRpc/Components/XmlRpcClient.cs @@ -45,7 +45,7 @@ namespace TouchSocket.XmlRpc return default; } - if (response.StatusCode != "200") + if (response.StatusCode != 200) { throw new Exception(response.StatusMessage); } @@ -78,7 +78,7 @@ namespace TouchSocket.XmlRpc { return; } - if (response.StatusCode != "200") + if (response.StatusCode != 200) { throw new Exception(response.StatusMessage); } diff --git a/src/TouchSocket.XmlRpc/Plugins/XmlRpcParserPlugin.cs b/src/TouchSocket.XmlRpc/Plugins/XmlRpcParserPlugin.cs index 9a06e72a1..b8e00a99e 100644 --- a/src/TouchSocket.XmlRpc/Plugins/XmlRpcParserPlugin.cs +++ b/src/TouchSocket.XmlRpc/Plugins/XmlRpcParserPlugin.cs @@ -24,6 +24,7 @@ namespace TouchSocket.XmlRpc /// /// XmlRpc解析器 /// + [PluginOption(Singleton = true, NotRegister = false)] public class XmlRpcParserPlugin : PluginBase, IRpcParser, IHttpPostPlugin { private string m_xmlRpcUrl = "/xmlrpc"; @@ -181,7 +182,7 @@ namespace TouchSocket.XmlRpc } else { - httpResponse.StatusCode = "201"; + httpResponse.StatusCode = 201; httpResponse.StatusMessage = invokeResult.Message; } try diff --git a/src/TouchSocket.XmlRpc/Resources/TouchSocketXmlRpcResource.cs b/src/TouchSocket.XmlRpc/Resources/TouchSocketXmlRpcResource.cs index 67aecf083..55af2e293 100644 --- a/src/TouchSocket.XmlRpc/Resources/TouchSocketXmlRpcResource.cs +++ b/src/TouchSocket.XmlRpc/Resources/TouchSocketXmlRpcResource.cs @@ -11,8 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.ComponentModel; - namespace TouchSocket.Resources { /// @@ -20,6 +18,6 @@ namespace TouchSocket.Resources /// public enum TouchSocketXmlRpcResource : byte { - + } } \ No newline at end of file diff --git a/src/TouchSocket.XmlRpc/TouchSocket.XmlRpc.csproj b/src/TouchSocket.XmlRpc/TouchSocket.XmlRpc.csproj index c70862c3e..bbab101a5 100644 --- a/src/TouchSocket.XmlRpc/TouchSocket.XmlRpc.csproj +++ b/src/TouchSocket.XmlRpc/TouchSocket.XmlRpc.csproj @@ -1,53 +1,21 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 XmlRpc 这是基于TouchSocket,能够提供XmlRpc的扩展功能组件。 - 说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt +说明文档:http://rrqm_home.gitee.io/touchsocket TouchSocket.XmlRpc - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket.XmlRpc + ..\..\Build\NugetPackages\TouchSocket.XmlRpc - - True - - - - True - - - - - - - - - - - - + + + True + Embedded + True + diff --git a/TouchSocket.sln b/src/TouchSocket.sln similarity index 78% rename from TouchSocket.sln rename to src/TouchSocket.sln index e74985765..0608a3798 100644 --- a/TouchSocket.sln +++ b/src/TouchSocket.sln @@ -3,29 +3,34 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.4.33122.133 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket", "src\TouchSocket\TouchSocket.csproj", "{37BF3CB2-9003-465D-A936-7373301FDA5C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket", "TouchSocket\TouchSocket.csproj", "{37BF3CB2-9003-465D-A936-7373301FDA5C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.AspNetCore", "src\TouchSocket.AspNetCore\TouchSocket.AspNetCore.csproj", "{6E00016F-41A4-40BC-AF9C-DA3B0FA4F81A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.AspNetCore", "TouchSocket.AspNetCore\TouchSocket.AspNetCore.csproj", "{6E00016F-41A4-40BC-AF9C-DA3B0FA4F81A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.CodeAnalyzer", "src\TouchSocket.CodeAnalyzer\TouchSocket.CodeAnalyzer.csproj", "{C489C644-2662-49BF-A9F1-C9631E4770AE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.CodeAnalyzer", "TouchSocket.CodeAnalyzer\TouchSocket.CodeAnalyzer.csproj", "{C489C644-2662-49BF-A9F1-C9631E4770AE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Core", "src\TouchSocket.Core\TouchSocket.Core.csproj", "{0E789C43-A0CA-4EBD-B7E9-E085AD5CFD41}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Core", "TouchSocket.Core\TouchSocket.Core.csproj", "{0E789C43-A0CA-4EBD-B7E9-E085AD5CFD41}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Core.DependencyInjection", "src\TouchSocket.Core.DependencyInjection\TouchSocket.Core.DependencyInjection.csproj", "{0CB42715-7C9C-4683-8A59-5472FF44A458}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Core.DependencyInjection", "TouchSocket.Core.DependencyInjection\TouchSocket.Core.DependencyInjection.csproj", "{0CB42715-7C9C-4683-8A59-5472FF44A458}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Http", "src\TouchSocket.Http\TouchSocket.Http.csproj", "{80374769-93F5-49B9-A95E-7E0D3BEBDE45}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Http", "TouchSocket.Http\TouchSocket.Http.csproj", "{80374769-93F5-49B9-A95E-7E0D3BEBDE45}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.JsonRpc", "src\TouchSocket.JsonRpc\TouchSocket.JsonRpc.csproj", "{5D01F692-E379-457B-B669-AE1740C2D112}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.JsonRpc", "TouchSocket.JsonRpc\TouchSocket.JsonRpc.csproj", "{5D01F692-E379-457B-B669-AE1740C2D112}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Rpc", "src\TouchSocket.Rpc\TouchSocket.Rpc.csproj", "{7EE9DA27-F93B-4232-88E8-4321FDB3A7EE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Rpc", "TouchSocket.Rpc\TouchSocket.Rpc.csproj", "{7EE9DA27-F93B-4232-88E8-4321FDB3A7EE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.SourceGenerator.Rpc", "src\TouchSocket.SourceGenerator.Rpc\TouchSocket.SourceGenerator.Rpc.csproj", "{79A7F310-F5E2-410C-B953-D5A501EE5185}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.SourceGenerator.Rpc", "TouchSocket.SourceGenerator.Rpc\TouchSocket.SourceGenerator.Rpc.csproj", "{79A7F310-F5E2-410C-B953-D5A501EE5185}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.WebApi", "src\TouchSocket.WebApi\TouchSocket.WebApi.csproj", "{AC6D4D92-37E4-4CF8-82E3-A8CB2BFCE96C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.WebApi", "TouchSocket.WebApi\TouchSocket.WebApi.csproj", "{AC6D4D92-37E4-4CF8-82E3-A8CB2BFCE96C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.XmlRpc", "src\TouchSocket.XmlRpc\TouchSocket.XmlRpc.csproj", "{51400DB7-74C1-45CA-A647-0052D58047E9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.XmlRpc", "TouchSocket.XmlRpc\TouchSocket.XmlRpc.csproj", "{51400DB7-74C1-45CA-A647-0052D58047E9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Dmtp", "src\TouchSocket.Dmtp\TouchSocket.Dmtp.csproj", "{660C6B92-190A-47FD-8E31-E2A01501C750}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TouchSocket.Dmtp", "TouchSocket.Dmtp\TouchSocket.Dmtp.csproj", "{660C6B92-190A-47FD-8E31-E2A01501C750}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "解决方案", "解决方案", "{05D0081C-1A4E-49C0-ADF0-C501CC454639}" + ProjectSection(SolutionItems) = preProject + Directory.Build.props = Directory.Build.props + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/TouchSocket/Common/DelaySender.cs b/src/TouchSocket/Common/DelaySender.cs index 0db15bf54..5554cabc1 100644 --- a/src/TouchSocket/Common/DelaySender.cs +++ b/src/TouchSocket/Common/DelaySender.cs @@ -33,20 +33,21 @@ namespace TouchSocket.Sockets /// 延迟发送器 /// /// - /// /// - public DelaySender(Socket socket, int queueLength, Action onError) + /// + public DelaySender(Socket socket, DelaySenderOption delaySenderOption, Action onError) { + this.DelayLength=delaySenderOption.DelayLength; this.m_socket = socket; this.m_onError = onError; - this.m_queueDatas = new IntelligentDataQueue(queueLength); + this.m_queueDatas = new IntelligentDataQueue(delaySenderOption.QueueLength); this.m_lockSlim = new ReaderWriterLockSlim(); } /// - /// 延迟包最大尺寸,默认1024*512字节。 + /// 延迟包最大尺寸。 /// - public int DelayLength { get; set; } = 1024 * 512; + public int DelayLength { get;private set; } /// /// 是否处于发送状态 diff --git a/src/TouchSocket/Common/IPHost.cs b/src/TouchSocket/Common/IPHost.cs index 14605fb7f..91f69707a 100644 --- a/src/TouchSocket/Common/IPHost.cs +++ b/src/TouchSocket/Common/IPHost.cs @@ -14,7 +14,6 @@ using System; using System.Collections.Generic; using System.Net; -using System.Net.Sockets; namespace TouchSocket.Sockets { @@ -55,7 +54,7 @@ namespace TouchSocket.Sockets /// public IPHost(int port) : this($"0.0.0.0:{port}") { - + } /// @@ -63,7 +62,7 @@ namespace TouchSocket.Sockets /// /// /// - public IPHost(IPAddress address,int port) : this($"{address}:{port}") + public IPHost(IPAddress address, int port) : this($"{address}:{port}") { } diff --git a/src/TouchSocket/Common/Options/DelaySenderOption.cs b/src/TouchSocket/Common/Options/DelaySenderOption.cs index a263c71ed..57ccaff9f 100644 --- a/src/TouchSocket/Common/Options/DelaySenderOption.cs +++ b/src/TouchSocket/Common/Options/DelaySenderOption.cs @@ -19,13 +19,13 @@ namespace TouchSocket.Sockets public class DelaySenderOption { /// - /// 延迟队列最大尺寸,默认1024*1024*10字节。 + /// 延迟队列最大尺寸,默认1024*1024字节。 /// - public int QueueLength { get; set; } = 1024 * 1024 * 10; + public int QueueLength { get; set; } = 1024 * 1024; /// - /// 延迟包最大尺寸,默认1024*512字节。 + /// 延迟包最大尺寸,默认1024*64字节。 /// - public int DelayLength { get; set; } = 1024 * 512; + public int DelayLength { get; set; } = 1024 * 64; } } \ No newline at end of file diff --git a/src/TouchSocket/Common/Protocol.cs b/src/TouchSocket/Common/Protocol.cs index 468270d59..dd4d24df7 100644 --- a/src/TouchSocket/Common/Protocol.cs +++ b/src/TouchSocket/Common/Protocol.cs @@ -98,7 +98,7 @@ namespace TouchSocket.Sockets /// public static bool operator ==(Protocol a, Protocol b) { - return string.IsNullOrEmpty(a.m_value) && string.IsNullOrEmpty(b.m_value)|| string.Equals(a.m_value, b.m_value); + return string.IsNullOrEmpty(a.m_value) && string.IsNullOrEmpty(b.m_value) || string.Equals(a.m_value, b.m_value); } /// diff --git a/src/TouchSocket/Common/TouchSocketUtility.cs b/src/TouchSocket/Common/TouchSocketUtility.cs index 109d51f11..5aea181f7 100644 --- a/src/TouchSocket/Common/TouchSocketUtility.cs +++ b/src/TouchSocket/Common/TouchSocketUtility.cs @@ -97,9 +97,9 @@ namespace TouchSocket.Sockets } } - /// - /// 大数据边界 - /// - public const int BigDataBoundary = 1024 * 64; + ///// + ///// 大数据边界 + ///// + //public const int BigDataBoundary = 1024 * 64; } } \ No newline at end of file diff --git a/src/TouchSocket/Components/Tcp/SocketClient.cs b/src/TouchSocket/Components/Tcp/SocketClient.cs index f22f506f3..66051d7a8 100644 --- a/src/TouchSocket/Components/Tcp/SocketClient.cs +++ b/src/TouchSocket/Components/Tcp/SocketClient.cs @@ -40,16 +40,14 @@ namespace TouchSocket.Sockets private int m_bufferRate = 1; private DelaySender m_delaySender; - private bool m_useDelaySender; private Stream m_workStream; - private bool m_online; #endregion 变量 #region 属性 /// - public bool CanSend => this.m_online; + public bool CanSend => this.Online; /// public virtual bool CanSetDataHandlingAdapter => true; @@ -76,7 +74,7 @@ namespace TouchSocket.Sockets public Socket MainSocket { get; private set; } /// - public bool Online { get => this.m_online;} + public bool Online { get; private set; } /// public IPluginsManager PluginsManager { get; private set; } @@ -87,6 +85,9 @@ namespace TouchSocket.Sockets /// public Protocol Protocol { get; set; } + /// + public ListenOption ListenOption { get; private set; } + /// public ReceiveType ReceiveType { get; private set; } @@ -155,7 +156,7 @@ namespace TouchSocket.Sockets internal void InternalConnected(ConnectedEventArgs e) { - this.m_online = true; + this.Online = true; this.OnConnected(e); @@ -163,15 +164,7 @@ namespace TouchSocket.Sockets { return; } - if (this.Config.GetValue(TouchSocketConfigExtension.DelaySenderProperty) is DelaySenderOption senderOption) - { - this.m_useDelaySender = true; - this.m_delaySender.SafeDispose(); - this.m_delaySender = new DelaySender(this.MainSocket, senderOption.QueueLength, this.OnDelaySenderError) - { - DelayLength = senderOption.DelayLength - }; - } + if (this.PluginsManager.Enable && this.PluginsManager.Raise(nameof(ITcpConnectedPlugin.OnTcpConnected), this, e)) { @@ -220,9 +213,11 @@ namespace TouchSocket.Sockets this.PluginsManager = pluginsManager; } - internal void InternalSetReceiveType(ReceiveType receiveType) + internal void InternalSetListenOption(ListenOption option) { - this.ReceiveType = receiveType; + this.ListenOption = option; + this.ReceiveType = option.ReceiveType; + this.SetBufferLength(option.BufferLength); } internal void InternalSetService(TcpServiceBase serviceBase) @@ -237,6 +232,11 @@ namespace TouchSocket.Sockets this.Port = mainSocket.RemoteEndPoint.GetPort(); this.ServiceIP = mainSocket.LocalEndPoint.GetIP(); this.ServicePort = mainSocket.LocalEndPoint.GetPort(); + + if (this.Config.GetValue(TouchSocketConfigExtension.DelaySenderProperty) is DelaySenderOption senderOption) + { + this.m_delaySender = new DelaySender(this.MainSocket, senderOption, this.OnDelaySenderError); + } } #endregion Internal @@ -318,7 +318,7 @@ namespace TouchSocket.Sockets return; } - if (this.PluginsManager.Enable && this.PluginsManager.Raise(nameof(ITcpDisconnectedPlguin.OnTcpDisconnected), this, e)) + if (this.PluginsManager.Enable && this.PluginsManager.Raise(nameof(ITcpDisconnectedPlugin.OnTcpDisconnected), this, e)) { return; } @@ -346,13 +346,14 @@ namespace TouchSocket.Sockets #endregion 事件&委托 - + /// public virtual void Close(string msg = TouchSocketCoreUtility.Empty) { + lock (this.SyncRoot) { - if (this.m_online) + if (this.Online) { this.MainSocket.TryClose(); this.PrivateOnDisconnecting(new DisconnectEventArgs(true, msg)); @@ -444,7 +445,7 @@ namespace TouchSocket.Sockets { lock (this.SyncRoot) { - if (this.m_online) + if (this.Online) { this.PrivateOnDisconnecting(new DisconnectEventArgs(true, $"{nameof(Dispose)}主动断开")); } @@ -544,16 +545,16 @@ namespace TouchSocket.Sockets { if (this.GetSocketCliectCollection().TryRemove(this.Id, out _)) { - if (this.m_online) + if (this.Online) { - this.m_online = false; + this.Online = false; this.MainSocket.SafeDispose(); this.m_delaySender.SafeDispose(); this.DataHandlingAdapter.SafeDispose(); this.PrivateOnDisconnected(new DisconnectEventArgs(manual, msg)); } } - + base.Dispose(true); } } @@ -711,7 +712,7 @@ namespace TouchSocket.Sockets public void DefaultSend(byte[] buffer, int offset, int length) { if (!this.CanSend) - { + { throw new NotConnectedException(TouchSocketResource.NotConnected.GetDescription()); } if (this.HandleSendingData(buffer, offset, length)) @@ -722,9 +723,9 @@ namespace TouchSocket.Sockets } else { - if (this.m_useDelaySender && length < TouchSocketUtility.BigDataBoundary) + if (this.m_delaySender!=null && length < this.m_delaySender.DelayLength) { - this.m_delaySender.Send(new QueueDataBytes(buffer, offset, length)); + this.m_delaySender.Send(QueueDataBytes.CreateNew(buffer, offset, length)); } else { diff --git a/src/TouchSocket/Components/Tcp/TcpClient.cs b/src/TouchSocket/Components/Tcp/TcpClient.cs index 414469731..af4048af0 100644 --- a/src/TouchSocket/Components/Tcp/TcpClient.cs +++ b/src/TouchSocket/Components/Tcp/TcpClient.cs @@ -13,10 +13,8 @@ using System; using System.Collections.Generic; using System.IO; -using System.Net; using System.Net.Security; using System.Net.Sockets; -using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; @@ -62,14 +60,10 @@ namespace TouchSocket.Sockets } #region 变量 - private DelaySender m_delaySender; - private bool m_useDelaySender; private Stream m_workStream; private int m_bufferRate = 1; private volatile bool m_online; - private Socket m_mainSocket; - #endregion 变量 #region 事件 @@ -152,7 +146,7 @@ namespace TouchSocket.Sockets { return; } - this.PluginsManager.Raise(nameof(ITcpDisconnectedPlguin.OnTcpDisconnected), this, e); + this.PluginsManager.Raise(nameof(ITcpDisconnectedPlugin.OnTcpDisconnected), this, e); } /// @@ -232,7 +226,7 @@ namespace TouchSocket.Sockets public string IP { get; private set; } /// - public Socket MainSocket { get => this.m_mainSocket; } + public Socket MainSocket { get; private set; } /// public bool Online { get => this.m_online; } @@ -352,13 +346,12 @@ namespace TouchSocket.Sockets } if (this.Config == null) { - throw new ArgumentNullException("配置文件不能为空。"); + throw new ArgumentNullException(nameof(this.Config),"配置文件不能为空。"); } - var iPHost = this.Config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty) ?? throw new ArgumentNullException("iPHost不能为空。"); + var iPHost = this.Config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty) ?? throw new ArgumentNullException(nameof(IPHost),"iPHost不能为空。"); this.MainSocket.SafeDispose(); var socket = this.CreateSocket(iPHost); - var args = new ConnectingEventArgs(this.MainSocket); - this.PrivateOnConnecting(args); + this.PrivateOnConnecting(new ConnectingEventArgs(this.MainSocket)); if (timeout == 5000) { socket.Connect(iPHost.Host, iPHost.Port); @@ -380,44 +373,54 @@ namespace TouchSocket.Sockets this.SetSocket(socket); this.BeginReceive(); this.PrivateOnConnected(new ConnectedEventArgs()); - - //; - //var result = this.MainSocket.BeginConnect(iPHost.Host, iPHost.Port, null, null); - //if (result.AsyncWaitHandle.WaitOne(timeout)) - //{ - // result. - // if (this.MainSocket.Connected) - // { - // this.MainSocket.EndConnect(result); - // this.m_online = true; - // this.LoadSocketAndReadIpPort(); - - // if (this.Config.GetValue(TouchSocketConfigExtension.DelaySenderProperty) is DelaySenderOption senderOption) - // { - // this.m_useDelaySender = true; - // this.m_delaySender.SafeDispose(); - // this.m_delaySender = new DelaySender(this.MainSocket, senderOption.QueueLength, this.OnDelaySenderError) - // { - // DelayLength = senderOption.DelayLength - // }; - // } - - // this.BeginReceive(); - // //this.PrivateOnConnected(new ConnectedEventArgs()); - // Task.Factory.StartNew(this.PrivateOnConnected, new ConnectedEventArgs()); - // return; - // } - // else - // { - // this.MainSocket.SafeDispose(); - // throw new Exception("异步已完成,但是socket并未在连接状态,可能发生了绑定端口占用的错误。"); - // } - //} - //this.MainSocket.SafeDispose(); - //throw new TimeoutException(); } } + //protected Task TcpConnectAsync(int timeout) + //{ + // lock (this.SyncRoot) + // { + // if (this.m_online) + // { + // return; + // } + // if (this.DisposedValue) + // { + // throw new ObjectDisposedException(this.GetType().FullName); + // } + // if (this.Config == null) + // { + // throw new ArgumentNullException("配置文件不能为空。"); + // } + // var iPHost = this.Config.GetValue(TouchSocketConfigExtension.RemoteIPHostProperty) ?? throw new ArgumentNullException("iPHost不能为空。"); + // this.MainSocket.SafeDispose(); + // var socket = this.CreateSocket(iPHost); + // var args = new ConnectingEventArgs(this.MainSocket); + // this.PrivateOnConnecting(args); + // if (timeout == 5000) + // { + // socket.Connect(iPHost.Host, iPHost.Port); + // } + // else + // { + // var task = Task.Run(() => + // { + // socket.Connect(iPHost.Host, iPHost.Port); + // }); + // task.ConfigureAwait(false); + // if (!task.Wait(timeout)) + // { + // socket.SafeDispose(); + // throw new TimeoutException(); + // } + // } + // this.m_online = true; + // this.SetSocket(socket); + // this.BeginReceive(); + // this.PrivateOnConnected(new ConnectedEventArgs()); + // } + //} + /// public virtual ITcpClient Connect(int timeout = 5000) { @@ -698,12 +701,25 @@ namespace TouchSocket.Sockets private Socket CreateSocket(IPHost iPHost) { - var socket = new Socket(iPHost.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) + Socket socket; + if (iPHost.HostNameType == UriHostNameType.Dns) { - ReceiveBufferSize = this.BufferLength, - SendBufferSize = this.BufferLength, - SendTimeout = this.Config.GetValue(TouchSocketConfigExtension.SendTimeoutProperty) - }; + socket = new Socket(SocketType.Stream, ProtocolType.Tcp) + { + ReceiveBufferSize = this.BufferLength, + SendBufferSize = this.BufferLength, + SendTimeout = this.Config.GetValue(TouchSocketConfigExtension.SendTimeoutProperty) + }; + } + else + { + socket = new Socket(iPHost.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) + { + ReceiveBufferSize = this.BufferLength, + SendBufferSize = this.BufferLength, + SendTimeout = this.Config.GetValue(TouchSocketConfigExtension.SendTimeoutProperty) + }; + } #if NET45_OR_GREATER var keepAliveValue = this.Config.GetValue(TouchSocketConfigExtension.KeepAliveValueProperty); @@ -715,7 +731,7 @@ namespace TouchSocket.Sockets #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - var keepAliveValue = Config.GetValue(TouchSocketConfigExtension.KeepAliveValueProperty); + var keepAliveValue = this.Config.GetValue(TouchSocketConfigExtension.KeepAliveValueProperty); if (keepAliveValue.Enable) { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); @@ -944,9 +960,9 @@ namespace TouchSocket.Sockets } else { - if (this.m_useDelaySender && length < TouchSocketUtility.BigDataBoundary) + if (this.m_delaySender!=null && length < m_delaySender.DelayLength) { - this.m_delaySender.Send(new QueueDataBytes(buffer, offset, length)); + this.m_delaySender.Send(QueueDataBytes.CreateNew(buffer, offset, length)); } else { @@ -988,7 +1004,12 @@ namespace TouchSocket.Sockets this.IP = socket.RemoteEndPoint.GetIP(); this.Port = socket.RemoteEndPoint.GetPort(); - this.m_mainSocket = socket; + this.MainSocket = socket; + var delaySenderOption = this.Config.GetValue(TouchSocketConfigExtension.DelaySenderProperty); + if (delaySenderOption != null) + { + this.m_delaySender = new DelaySender(socket, delaySenderOption, this.OnDelaySenderError); + } } private void ProcessReceived(SocketAsyncEventArgs e) diff --git a/src/TouchSocket/Components/Tcp/TcpService.cs b/src/TouchSocket/Components/Tcp/TcpService.cs index 86c0c499b..fcd19b9f0 100644 --- a/src/TouchSocket/Components/Tcp/TcpService.cs +++ b/src/TouchSocket/Components/Tcp/TcpService.cs @@ -257,7 +257,7 @@ namespace TouchSocket.Sockets throw new ArgumentNullException(nameof(option.IpHost)); } - var socket = new Socket(option.IpHost.EndPoint.AddressFamily,SocketType.Stream, ProtocolType.Tcp); + var socket = new Socket(option.IpHost.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (option.ReuseAddress) { @@ -360,7 +360,7 @@ namespace TouchSocket.Sockets /// public override IService Setup(TouchSocketConfig config) { - + if (config == null) { throw new ArgumentNullException(nameof(config)); @@ -656,7 +656,7 @@ namespace TouchSocket.Sockets var socket = e.AcceptSocket; if (this.SocketClients.Count < this.m_maxCount) { - this.OnClientSocketInit(socket, (TcpNetworkMonitor)e.UserToken); + Task.Factory.StartNew(this.OnClientSocketInit, Tuple.Create(socket, (TcpNetworkMonitor)e.UserToken)); } else { @@ -681,8 +681,12 @@ namespace TouchSocket.Sockets } } - private void OnClientSocketInit(Socket socket, TcpNetworkMonitor monitor) + private void OnClientSocketInit(object obj) { + var tuple = (Tuple)obj; + var socket = tuple.Item1; + var monitor = tuple.Item2; + try { if (monitor.Options.NoDelay) @@ -697,10 +701,10 @@ namespace TouchSocket.Sockets client.InternalSetConfig(this.m_config); client.InternalSetContainer(this.m_container); client.InternalSetService(this); - client.InternalSetReceiveType(monitor.Options.ReceiveType); + client.InternalSetListenOption(monitor.Options); client.InternalSetSocket(socket); client.InternalSetPluginsManager(this.m_pluginsManager); - client.SetBufferLength(monitor.Options.BufferLength); + if (client.CanSetDataHandlingAdapter) { client.SetDataHandlingAdapter(monitor.Options.TcpAdapter.Invoke()); diff --git a/src/TouchSocket/Components/Udp/UdpSession.cs b/src/TouchSocket/Components/Udp/UdpSession.cs index 565f6b184..d57798223 100644 --- a/src/TouchSocket/Components/Udp/UdpSession.cs +++ b/src/TouchSocket/Components/Udp/UdpSession.cs @@ -467,7 +467,7 @@ namespace TouchSocket.Sockets { var threadCount = this.Config.GetValue(TouchSocketConfigExtension.ThreadCountProperty); threadCount = threadCount < 0 ? 1 : threadCount; - var socket = new Socket( SocketType.Dgram, ProtocolType.Udp) + var socket = new Socket(iPHost.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp) { ReceiveBufferSize = BufferLength, SendBufferSize = BufferLength, @@ -521,24 +521,24 @@ namespace TouchSocket.Sockets #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - for (int i = 0; i < threadCount; i++) + for (var i = 0; i < threadCount; i++) { - SocketAsyncEventArgs eventArg = new SocketAsyncEventArgs(); - m_socketAsyncs.Add(eventArg); - eventArg.Completed += IO_Completed; - ByteBlock byteBlock = new ByteBlock(BufferLength); + var eventArg = new SocketAsyncEventArgs(); + this.m_socketAsyncs.Add(eventArg); + eventArg.Completed += this.IO_Completed; + var byteBlock = new ByteBlock(this.BufferLength); eventArg.UserToken = byteBlock; eventArg.SetBuffer(byteBlock.Buffer, 0, byteBlock.Capacity); eventArg.RemoteEndPoint = iPHost.EndPoint; if (!socket.ReceiveFromAsync(eventArg)) { - ProcessReceive(socket, eventArg); + this.ProcessReceive(socket, eventArg); } } } else { - Thread thread = new Thread(Received); + var thread = new Thread(this.Received); thread.IsBackground = true; thread.Start(); } @@ -557,7 +557,7 @@ namespace TouchSocket.Sockets var byteBlock = new ByteBlock(); try { - EndPoint endPoint = this.Monitor.IPHost.EndPoint; + var endPoint = this.Monitor.IPHost.EndPoint; var r = this.Monitor.Socket.ReceiveFrom(byteBlock.Buffer, ref endPoint); byteBlock.SetLength(r); this.HandleBuffer(endPoint, byteBlock); diff --git a/src/TouchSocket/DataAdapter/Custom/CustomBigFixedHeaderDataHandlingAdapter.cs b/src/TouchSocket/DataAdapter/Custom/CustomBigFixedHeaderDataHandlingAdapter.cs index 5e279c295..56c1e1a07 100644 --- a/src/TouchSocket/DataAdapter/Custom/CustomBigFixedHeaderDataHandlingAdapter.cs +++ b/src/TouchSocket/DataAdapter/Custom/CustomBigFixedHeaderDataHandlingAdapter.cs @@ -46,7 +46,7 @@ namespace TouchSocket.Sockets var r = (int)Math.Min(this.m_surLen, byteBlock.CanReadLen); try { - var bytes = byteBlock.ToArray(byteBlock.Pos,r); + var bytes = byteBlock.ToArray(byteBlock.Pos, r); request.OnAppendBody(bytes); this.m_surLen -= r; byteBlock.Pos += r; diff --git a/src/TouchSocket/DataAdapter/Custom/CustomFixedHeaderByteBlockDataHandlingAdapter.cs b/src/TouchSocket/DataAdapter/Custom/CustomFixedHeaderByteBlockDataHandlingAdapter.cs index fbcceddfa..986ea8b7b 100644 --- a/src/TouchSocket/DataAdapter/Custom/CustomFixedHeaderByteBlockDataHandlingAdapter.cs +++ b/src/TouchSocket/DataAdapter/Custom/CustomFixedHeaderByteBlockDataHandlingAdapter.cs @@ -71,7 +71,7 @@ namespace TouchSocket.Sockets request = requestInfo; if (requestInfo.BodyLength > byteBlock.CanReadLen)//body不满足解析,开始缓存,然后保存对象 { - tempCapacity= requestInfo.BodyLength+this.HeaderLength; + tempCapacity = requestInfo.BodyLength + this.HeaderLength; return FilterResult.Cache; } diff --git a/src/TouchSocket/DataAdapter/Test/TcpDataAdapterTester.cs b/src/TouchSocket/DataAdapter/Test/TcpDataAdapterTester.cs index 4589edfa9..62c8ecddf 100644 --- a/src/TouchSocket/DataAdapter/Test/TcpDataAdapterTester.cs +++ b/src/TouchSocket/DataAdapter/Test/TcpDataAdapterTester.cs @@ -13,7 +13,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Net; using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; diff --git a/src/TouchSocket/DataAdapter/Test/UdpDataAdapterTester.cs b/src/TouchSocket/DataAdapter/Test/UdpDataAdapterTester.cs index d436101d3..d6bad880b 100644 --- a/src/TouchSocket/DataAdapter/Test/UdpDataAdapterTester.cs +++ b/src/TouchSocket/DataAdapter/Test/UdpDataAdapterTester.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Net; -using System.Text; using System.Threading; using System.Threading.Tasks; using TouchSocket.Core; diff --git a/src/TouchSocket/EventArgs/ConnectedEventArgs.cs b/src/TouchSocket/EventArgs/ConnectedEventArgs.cs index f323914bd..287c7b607 100644 --- a/src/TouchSocket/EventArgs/ConnectedEventArgs.cs +++ b/src/TouchSocket/EventArgs/ConnectedEventArgs.cs @@ -1,16 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using TouchSocket.Core; +using TouchSocket.Core; namespace TouchSocket.Sockets { /// /// ConnectedEventArgs /// - public class ConnectedEventArgs: PluginEventArgs + public class ConnectedEventArgs : PluginEventArgs { } } diff --git a/src/TouchSocket/EventArgs/DisconnectEventArgs.cs b/src/TouchSocket/EventArgs/DisconnectEventArgs.cs index 2713010f4..12447e31c 100644 --- a/src/TouchSocket/EventArgs/DisconnectEventArgs.cs +++ b/src/TouchSocket/EventArgs/DisconnectEventArgs.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System; using TouchSocket.Core; namespace TouchSocket.Sockets diff --git a/src/TouchSocket/EventArgs/IdChangedEventArgs.cs b/src/TouchSocket/EventArgs/IdChangedEventArgs.cs index bf6bf752a..812cd09f0 100644 --- a/src/TouchSocket/EventArgs/IdChangedEventArgs.cs +++ b/src/TouchSocket/EventArgs/IdChangedEventArgs.cs @@ -24,7 +24,7 @@ namespace TouchSocket.Sockets /// /// /// - public IdChangedEventArgs(string oldId, string newId) + public IdChangedEventArgs(string oldId, string newId) { this.OldId = oldId; this.NewId = newId; diff --git a/src/TouchSocket/Extensions/DataHandlingAdapterExtension.cs b/src/TouchSocket/Extensions/DataHandlingAdapterExtension.cs index 69b45f1f0..77e2237c4 100644 --- a/src/TouchSocket/Extensions/DataHandlingAdapterExtension.cs +++ b/src/TouchSocket/Extensions/DataHandlingAdapterExtension.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -19,7 +15,7 @@ namespace TouchSocket.Sockets /// /// /// - public static void Config(this TcpDataHandlingAdapter adapter,TouchSocketConfig config) + public static void Config(this TcpDataHandlingAdapter adapter, TouchSocketConfig config) { if (config.GetValue(TouchSocketConfigExtension.MaxPackageSizeProperty) is int v1) { diff --git a/src/TouchSocket/Extensions/SocketPluginsManagerExtension.cs b/src/TouchSocket/Extensions/SocketPluginsManagerExtension.cs index cda91515e..bb41a34e5 100644 --- a/src/TouchSocket/Extensions/SocketPluginsManagerExtension.cs +++ b/src/TouchSocket/Extensions/SocketPluginsManagerExtension.cs @@ -13,7 +13,6 @@ using System; using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Sockets { diff --git a/src/TouchSocket/Extensions/TouchSocketConfigExtension.cs b/src/TouchSocket/Extensions/TouchSocketConfigExtension.cs index ddc6454ba..2f047a993 100644 --- a/src/TouchSocket/Extensions/TouchSocketConfigExtension.cs +++ b/src/TouchSocket/Extensions/TouchSocketConfigExtension.cs @@ -12,7 +12,6 @@ //------------------------------------------------------------------------------ using System; using System.Collections.Generic; -using System.Threading; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -301,7 +300,7 @@ namespace TouchSocket.Sockets /// public static TouchSocketConfig UseUdpReceive(this TouchSocketConfig config) { - return SetBindIPHost(config,0); + return SetBindIPHost(config, 0); } /// @@ -527,7 +526,7 @@ namespace TouchSocket.Sockets /// /// /// - public static TClient BuildClient(this TouchSocketConfig config) where TClient :ITcpClient,new () + public static TClient BuildClient(this TouchSocketConfig config) where TClient : ITcpClient, new() { var client = new TClient(); client.Setup(config); @@ -551,9 +550,9 @@ namespace TouchSocket.Sockets /// /// /// - public static TService BuildService(this TouchSocketConfig config) where TService : ITcpService ,new () + public static TService BuildService(this TouchSocketConfig config) where TService : ITcpService, new() { - var service =new TService(); + var service = new TService(); service.Setup(config); service.Start(); return service; diff --git a/src/TouchSocket/Interface/IClient.cs b/src/TouchSocket/Interface/IClient.cs index d187a0b41..f744c41ab 100644 --- a/src/TouchSocket/Interface/IClient.cs +++ b/src/TouchSocket/Interface/IClient.cs @@ -18,7 +18,7 @@ namespace TouchSocket.Sockets /// /// 终端接口 /// - public interface IClient : IDependencyObject, IDisposable,ISocket + public interface IClient : IDependencyObject, IDisposable, ISocket { /// diff --git a/src/TouchSocket/Interface/ISocketClient.cs b/src/TouchSocket/Interface/ISocketClient.cs index 3239ee3a3..9fe4ae2a5 100644 --- a/src/TouchSocket/Interface/ISocketClient.cs +++ b/src/TouchSocket/Interface/ISocketClient.cs @@ -43,5 +43,13 @@ namespace TouchSocket.Sockets /// 接收此客户端的服务器端口 /// int ServicePort { get; } + + /// + /// 监听配置。 + /// + /// 注意:一般情况下不要随意修改该值。 + /// + /// + ListenOption ListenOption { get; } } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/CheckClearPlugin.cs b/src/TouchSocket/Plugins/CheckClearPlugin.cs index 28ccdbbef..13d7f55d0 100644 --- a/src/TouchSocket/Plugins/CheckClearPlugin.cs +++ b/src/TouchSocket/Plugins/CheckClearPlugin.cs @@ -50,54 +50,19 @@ namespace TouchSocket.Sockets /// public CheckClearType CheckClearType { get; set; } = CheckClearType.All; - /// - /// 获取或设置清理无数据交互的Client,默认60秒。 - /// - public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(60); - /// /// 当因为超出时间限定而关闭。 /// public Action OnClose { get; set; } - /// - /// 清理统计类型。默认为:。当设置为时, - /// 则只检验发送方向是否有数据流动。没有的话则会断开连接。 + /// 获取或设置清理无数据交互的Client,默认60秒。 /// - /// - /// - public CheckClearPlugin SetCheckClearType(CheckClearType clearType) - { - this.CheckClearType = clearType; - return this; - } - - /// - /// 设置清理无数据交互的Client,默认60秒。 - /// - /// - /// - public CheckClearPlugin SetTick(TimeSpan timeSpan) - { - this.Tick = timeSpan; - return this; - } - - /// - /// 当因为超出时间限定而关闭。 - /// - /// - /// - public CheckClearPlugin SetOnClose(Action action) - { - this.OnClose = action; - return this; - } + public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(60); Task ITcpConnectedPlugin.OnTcpConnected(TClient client, ConnectedEventArgs e) { - Task.Run(async() => + Task.Run(async () => { while (true) { @@ -130,7 +95,41 @@ namespace TouchSocket.Sockets } }); - return e.InvokeNext(); + return e.InvokeNext(); + } + + /// + /// 清理统计类型。默认为:。当设置为时, + /// 则只检验发送方向是否有数据流动。没有的话则会断开连接。 + /// + /// + /// + public CheckClearPlugin SetCheckClearType(CheckClearType clearType) + { + this.CheckClearType = clearType; + return this; + } + + /// + /// 当因为超出时间限定而关闭。 + /// + /// + /// + public CheckClearPlugin SetOnClose(Action action) + { + this.OnClose = action; + return this; + } + + /// + /// 设置清理无数据交互的Client,默认60秒。 + /// + /// + /// + public CheckClearPlugin SetTick(TimeSpan timeSpan) + { + this.Tick = timeSpan; + return this; } } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/HeartbeatPlugin.cs b/src/TouchSocket/Plugins/HeartbeatPlugin.cs index e8620caa7..21a978a93 100644 --- a/src/TouchSocket/Plugins/HeartbeatPlugin.cs +++ b/src/TouchSocket/Plugins/HeartbeatPlugin.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -10,16 +6,51 @@ namespace TouchSocket.Sockets /// /// HeartbeatPlugin /// - public abstract class HeartbeatPlugin:PluginBase + public abstract class HeartbeatPlugin : PluginBase { /// - /// 获取或设置清理无数据交互的Client,默认60秒。 + /// 最大失败次数,默认3。 /// - public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(60); + public int MaxFailCount { get; set; } = 3; - protected void BeginHeartbeat() - { - + /// + /// 心跳间隔。默认3秒。 + /// + public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(3); + + } + + /// + /// HeartbeatPluginExtension + /// + public static class HeartbeatPluginExtension + { + /// + /// 设置心跳间隔。默认3秒。 + /// + /// + /// + /// + /// + public static THeartbeatPlugin SetTick(this THeartbeatPlugin heartbeatPlugin, TimeSpan timeSpan) + where THeartbeatPlugin : HeartbeatPlugin + { + heartbeatPlugin.Tick = timeSpan; + return heartbeatPlugin; + } + + /// + /// 设置最大失败次数,默认3。 + /// + /// + /// + /// + /// + public static THeartbeatPlugin SetMaxFailCount(this THeartbeatPlugin heartbeatPlugin,int value) + where THeartbeatPlugin : HeartbeatPlugin + { + heartbeatPlugin.MaxFailCount = value; + return heartbeatPlugin; } } } diff --git a/src/TouchSocket/Plugins/Interfaces/IIdChangedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/IIdChangedPlugin.cs index acd0f421f..a3f37d982 100644 --- a/src/TouchSocket/Plugins/Interfaces/IIdChangedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/IIdChangedPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -10,7 +6,7 @@ namespace TouchSocket.Sockets /// /// IIdChangedPlugin /// - public interface IIdChangedPlugin:IPlugin where TClient: IClient + public interface IIdChangedPlugin : IPlugin where TClient : IClient { /// /// 当Client的Id被更改后触发 @@ -25,7 +21,7 @@ namespace TouchSocket.Sockets /// IIdChangedPlugin /// public interface IIdChangedPlugin : IIdChangedPlugin - { - + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ILoadedConfigPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ILoadedConfigPlugin.cs index de9ec22d5..e2db47575 100644 --- a/src/TouchSocket/Plugins/Interfaces/ILoadedConfigPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ILoadedConfigPlugin.cs @@ -10,7 +10,6 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ -using System.ComponentModel; using System.Threading.Tasks; using TouchSocket.Core; @@ -33,8 +32,8 @@ namespace TouchSocket.Sockets /// /// 当配置Config完成时触发。 /// - public interface ILoadedConfigPlugin:ILoadedConfigPlugin - { - + public interface ILoadedConfigPlugin : ILoadedConfigPlugin + { + } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/Interfaces/ILoadingConfigPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ILoadingConfigPlugin.cs index 20774581b..d7dcf3935 100644 --- a/src/TouchSocket/Plugins/Interfaces/ILoadingConfigPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ILoadingConfigPlugin.cs @@ -1,17 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; -using TouchSocket.Sockets; namespace TouchSocket.Sockets { /// /// 当正在配置Config时触发。 /// - public interface ILoadingConfigPlugin:IPlugin + public interface ILoadingConfigPlugin : IPlugin { /// /// 当载入配置时 @@ -24,8 +19,8 @@ namespace TouchSocket.Sockets /// /// ILoadingConfigPlugin /// - public interface ILoadingConfigPlugin: ILoadingConfigPlugin - { - + public interface ILoadingConfigPlugin : ILoadingConfigPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/IServerStartedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/IServerStartedPlugin.cs index fde10d0c4..4f06a738c 100644 --- a/src/TouchSocket/Plugins/Interfaces/IServerStartedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/IServerStartedPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -10,7 +6,7 @@ namespace TouchSocket.Sockets /// /// IServerStartedPlugin /// - public interface IServerStartedPlugin:IPlugin where TServer : IService + public interface IServerStartedPlugin : IPlugin where TServer : IService { /// @@ -28,8 +24,8 @@ namespace TouchSocket.Sockets /// /// IServerStartedPlugin /// - public interface IServerStartedPlugin: IServerStartedPlugin - { - + public interface IServerStartedPlugin : IServerStartedPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/IServerStopedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/IServerStopedPlugin.cs index c6c4fcbe9..b54614203 100644 --- a/src/TouchSocket/Plugins/Interfaces/IServerStopedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/IServerStopedPlugin.cs @@ -7,7 +7,7 @@ namespace TouchSocket.Sockets /// /// IServerStopedPlugin /// - public interface IServerStopedPlugin : IPlugin where TServer:IService + public interface IServerStopedPlugin : IPlugin where TServer : IService { /// /// 当服务器调用或者时 @@ -20,8 +20,8 @@ namespace TouchSocket.Sockets /// /// IServerStopedPlugin /// - public interface IServerStopedPlugin: IServerStopedPlugin - { - + public interface IServerStopedPlugin : IServerStopedPlugin + { + } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpConnectedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpConnectedPlugin.cs index e7975738f..9931647b2 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpConnectedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpConnectedPlugin.cs @@ -6,7 +6,7 @@ namespace TouchSocket.Sockets /// /// 具有完成连接动作的插件接口 /// - public interface ITcpConnectedPlugin : IPlugin where TClient: IClient + public interface ITcpConnectedPlugin : IPlugin where TClient : IClient { /// /// 客户端连接成功后触发 @@ -20,8 +20,8 @@ namespace TouchSocket.Sockets /// /// ITcpConnectedPlugin /// - public interface ITcpConnectedPlugin: ITcpConnectedPlugin - { - + public interface ITcpConnectedPlugin : ITcpConnectedPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpConnectingPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpConnectingPlugin.cs index 4276197aa..e439f456f 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpConnectingPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpConnectingPlugin.cs @@ -6,7 +6,7 @@ namespace TouchSocket.Sockets /// /// 具有预备连接的插件接口 /// - public interface ITcpConnectingPlugin : IPlugin where TClient: IClient + public interface ITcpConnectingPlugin : IPlugin where TClient : IClient { /// /// 在即将完成连接时触发。 @@ -20,8 +20,8 @@ namespace TouchSocket.Sockets /// /// ITcpConnectingPlugin /// - public interface ITcpConnectingPlugin: ITcpConnectingPlugin - { - + public interface ITcpConnectingPlugin : ITcpConnectingPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlguin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlugin.cs similarity index 70% rename from src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlguin.cs rename to src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlugin.cs index 3618d56cc..0fe671678 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlguin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectedPlugin.cs @@ -6,7 +6,7 @@ namespace TouchSocket.Sockets /// /// 具有断开连接的插件接口 /// - public interface ITcpDisconnectedPlguin : IPlugin where TClient: IClient + public interface ITcpDisconnectedPlugin : IPlugin where TClient : IClient { /// /// 会话断开后触发 @@ -18,10 +18,10 @@ namespace TouchSocket.Sockets } /// - /// ITcpDisconnectedPlguin + /// ITcpDisconnectedPlugin /// - public interface ITcpDisconnectedPlguin: ITcpDisconnectedPlguin - { - + public interface ITcpDisconnectedPlugin : ITcpDisconnectedPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectingPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectingPlugin.cs index 8752175f7..2005877d5 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectingPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpDisconnectingPlugin.cs @@ -24,8 +24,8 @@ namespace TouchSocket.Sockets /// /// ITcpDisconnectingPlugin /// - public interface ITcpDisconnectingPlugin: ITcpDisconnectingPlugin - { - + public interface ITcpDisconnectingPlugin : ITcpDisconnectingPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpReceivedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpReceivedPlugin.cs index c261f418f..44d77db84 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpReceivedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpReceivedPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -10,7 +6,7 @@ namespace TouchSocket.Sockets /// /// ITcpReceivedPlugin /// - public interface ITcpReceivedPlugin:IPlugin where TClient : ITcpClientBase + public interface ITcpReceivedPlugin : IPlugin where TClient : ITcpClientBase { /// /// 在收到数据时触发 @@ -25,8 +21,8 @@ namespace TouchSocket.Sockets /// /// ITcpReceivedPlugin /// - public interface ITcpReceivedPlugin: ITcpReceivedPlugin - { - + public interface ITcpReceivedPlugin : ITcpReceivedPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpReceivingPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpReceivingPlugin.cs index 962b8e070..52bd88d48 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpReceivingPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpReceivingPlugin.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TouchSocket.Core; namespace TouchSocket.Sockets @@ -10,7 +6,7 @@ namespace TouchSocket.Sockets /// /// ITcpReceivingPlugin /// - public interface ITcpReceivingPlugin:IPlugin where TClient : ITcpClientBase + public interface ITcpReceivingPlugin : IPlugin where TClient : ITcpClientBase { /// /// 在刚收到数据时触发,即在适配器之前。 @@ -24,8 +20,8 @@ namespace TouchSocket.Sockets /// /// ITcpReceivingPlugin /// - public interface ITcpReceivingPlugin: ITcpReceivingPlugin - { - + public interface ITcpReceivingPlugin : ITcpReceivingPlugin + { + } } diff --git a/src/TouchSocket/Plugins/Interfaces/ITcpSendingPlugin.cs b/src/TouchSocket/Plugins/Interfaces/ITcpSendingPlugin.cs index c794aa4ef..f94d519be 100644 --- a/src/TouchSocket/Plugins/Interfaces/ITcpSendingPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/ITcpSendingPlugin.cs @@ -32,8 +32,8 @@ namespace TouchSocket.Sockets /// /// ITcpSendingPlugin /// - public interface ITcpSendingPlugin: ITcpSendingPlugin - { - + public interface ITcpSendingPlugin : ITcpSendingPlugin + { + } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/Interfaces/IUdpReceivedPlugin.cs b/src/TouchSocket/Plugins/Interfaces/IUdpReceivedPlugin.cs index 2ce558d53..ea53df50a 100644 --- a/src/TouchSocket/Plugins/Interfaces/IUdpReceivedPlugin.cs +++ b/src/TouchSocket/Plugins/Interfaces/IUdpReceivedPlugin.cs @@ -32,8 +32,8 @@ namespace TouchSocket.Sockets /// /// IUdpReceivedPlugin /// - public interface IUdpReceivedPlugin: IUdpReceivedPlugin - { - + public interface IUdpReceivedPlugin : IUdpReceivedPlugin + { + } } \ No newline at end of file diff --git a/src/TouchSocket/Plugins/ReconnectionPlugin.cs b/src/TouchSocket/Plugins/ReconnectionPlugin.cs index e99ae2908..2209fe79f 100644 --- a/src/TouchSocket/Plugins/ReconnectionPlugin.cs +++ b/src/TouchSocket/Plugins/ReconnectionPlugin.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; -using System.Net.Sockets; using System.Threading.Tasks; using TouchSocket.Core; @@ -21,8 +20,10 @@ namespace TouchSocket.Sockets /// 重连插件 /// [PluginOption(Singleton = true, NotRegister = true)] - public sealed partial class ReconnectionPlugin : PluginBase, ILoadedConfigPlugin, ITcpDisconnectedPlguin where TClient : class, ITcpClient + public sealed partial class ReconnectionPlugin : PluginBase, ILoadedConfigPlugin, ITcpDisconnectedPlugin where TClient : class, ITcpClient { + private bool m_polling; + /// /// 初始化一个重连插件 /// @@ -31,69 +32,21 @@ namespace TouchSocket.Sockets this.Order = int.MinValue; } - /// - /// ActionForConnect - /// - public Func> ActionForConnect { get; set; } - - /// - /// 设置连接动作 - /// - /// - /// 无论如何,只要返回True,则结束本轮尝试 - public ReconnectionPlugin SetConnectAction(Func> tryConnect) - { - this.ActionForConnect = tryConnect; - return this; - } - - private bool m_polling; - /// /// 每个周期可执行的委托。用于检验客户端活性。返回true表示存活,返回 /// public Func> ActionForCheck { get; set; } + /// + /// ActionForConnect + /// + public Func> ActionForConnect { get; set; } + /// /// 检验时间间隔 /// public TimeSpan Tick { get; set; } = TimeSpan.FromSeconds(1); - /// - /// 每个周期可执行的委托。返回值为True标识客户端存活。返回False,表示失活,立即重连。返回null时,表示跳过此次检验。 - /// - /// - /// - public ReconnectionPlugin SetActionForCheck(Func> actionForCheck) - { - this.ActionForCheck = actionForCheck; - return this; - } - - /// - /// 检验时间间隔 - /// - /// - /// - public ReconnectionPlugin SetTick(TimeSpan tick) - { - this.Tick = tick; - return this; - } - - /// - /// 使用轮询保持活性。 - /// - public ReconnectionPlugin UsePolling() - { - this.ActionForCheck = (client, failCount) => - { - return Task.FromResult(client?.Online); - }; - this.m_polling = true; - return this; - } - Task ILoadedConfigPlugin.OnLoadedConfig(object sender, ConfigEventArgs e) { Task.Run(async () => @@ -141,9 +94,9 @@ namespace TouchSocket.Sockets return e.InvokeNext(); } - Task ITcpDisconnectedPlguin.OnTcpDisconnected(TClient client, DisconnectEventArgs e) + Task ITcpDisconnectedPlugin.OnTcpDisconnected(TClient client, DisconnectEventArgs e) { - Task.Run(async() => + Task.Run(async () => { if (e.Manual) { @@ -161,5 +114,51 @@ namespace TouchSocket.Sockets return e.InvokeNext(); } + + /// + /// 每个周期可执行的委托。返回值为True标识客户端存活。返回False,表示失活,立即重连。返回null时,表示跳过此次检验。 + /// + /// + /// + public ReconnectionPlugin SetActionForCheck(Func> actionForCheck) + { + this.ActionForCheck = actionForCheck; + return this; + } + + /// + /// 设置连接动作 + /// + /// + /// 无论如何,只要返回True,则结束本轮尝试 + public ReconnectionPlugin SetConnectAction(Func> tryConnect) + { + this.ActionForConnect = tryConnect; + return this; + } + + /// + /// 检验时间间隔 + /// + /// + /// + public ReconnectionPlugin SetTick(TimeSpan tick) + { + this.Tick = tick; + return this; + } + + /// + /// 使用轮询保持活性。 + /// + public ReconnectionPlugin UsePolling() + { + this.ActionForCheck = (client, failCount) => + { + return Task.FromResult(client?.Online); + }; + this.m_polling = true; + return this; + } } } \ No newline at end of file diff --git a/src/TouchSocket/TouchSocket.csproj b/src/TouchSocket/TouchSocket.csproj index ec0adef3b..ca7d0e425 100644 --- a/src/TouchSocket/TouchSocket.csproj +++ b/src/TouchSocket/TouchSocket.csproj @@ -1,50 +1,20 @@ - net45;netstandard2.0;netcoreapp3.1;net7.0 - logo.ico - false - - 2.0.0-beta - true - 8.0 - True - 若汝棋茗 - Copyright © 2023 若汝棋茗 + net45;netstandard2.0;net6.0;net7.0 message;arraypool;logger;plugin TouchSocket是.Net(包括 C# 、VB.Net、F#)的一个整合性的socket网络通信框架。包含了 tcp、udp、ssl等一系列的通信模块。一键式解决 tcp 黏分包问题,udp大数据包分片组合问题等。使用协议模板,可快速实现「固定包头」、「固定长度」、「区间字符」等一系列的数据报文解析。 -说明文档:http://rrqm_home.gitee.io/touchsocket - https://gitee.com/rrqm_home/touchsocket - - true - true - logo.png - 若汝棋茗 - true - LICENSE.txt +说明文档:http://rrqm_home.gitee.io/touchsocket TouchSocket - ..\Build - - https://gitee.com/rrqm_home/touchsocket - ..\Build\NugetPackages\TouchSocket + ..\..\Build\NugetPackages\TouchSocket - - True - - - - True - - - - - - - - - - + + + True + Embedded + True + diff --git a/src/TouchSocket/WaitingClient/WaitingClient.cs b/src/TouchSocket/WaitingClient/WaitingClient.cs index 4de67ef6b..91bd2c838 100644 --- a/src/TouchSocket/WaitingClient/WaitingClient.cs +++ b/src/TouchSocket/WaitingClient/WaitingClient.cs @@ -118,7 +118,7 @@ namespace TouchSocket.Sockets { try { - m_semaphoreSlim.Wait(); + this.m_semaphoreSlim.Wait(); this.m_breaked = false; this.Reset(); if (this.WaitingOptions.BreakTrigger && this.Client is ITcpClientBase tcpClient) @@ -178,7 +178,7 @@ namespace TouchSocket.Sockets } finally { - m_semaphoreSlim.Release(); + this.m_semaphoreSlim.Release(); if (this.WaitingOptions.BreakTrigger && this.Client is ITcpClientBase tcpClient) { tcpClient.Disconnected -= this.OnDisconnected; @@ -213,7 +213,7 @@ namespace TouchSocket.Sockets { try { - m_semaphoreSlim.Wait(); + await this.m_semaphoreSlim.WaitAsync(); this.m_breaked = false; this.Reset(); if (this.WaitingOptions.BreakTrigger && this.Client is ITcpClientBase tcpClient) @@ -273,7 +273,7 @@ namespace TouchSocket.Sockets } finally { - m_semaphoreSlim.Release(); + this.m_semaphoreSlim.Release(); if (this.WaitingOptions.BreakTrigger && this.Client is ITcpClientBase tcpClient) { tcpClient.Disconnected -= this.OnDisconnected; diff --git a/src/TouchSocket/WaitingClient/WaitingClientExtension.cs b/src/TouchSocket/WaitingClient/WaitingClientExtension.cs index c1c2f4db1..4365abfcb 100644 --- a/src/TouchSocket/WaitingClient/WaitingClientExtension.cs +++ b/src/TouchSocket/WaitingClient/WaitingClientExtension.cs @@ -11,7 +11,6 @@ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ using System; -using TouchSocket.Core; namespace TouchSocket.Sockets {