diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 11d616e00..b0c2ba261 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -4,6 +4,7 @@ on: push: branches: - master + - 2refactory jobs: build: diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..f1decdffe --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "dotnet.defaultSolution": "SuperSocket.sln" +} \ No newline at end of file diff --git a/Directory.Build.props b/Directory.Build.props index a7619475a..de9ecab16 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - 8.0 + 10.0 netstandard2.1;net5.0;net6.0;net7.0;net8.0 net7.0 diff --git a/SuperSocket.sln b/SuperSocket.sln index e463107a6..e101b4eff 100644 --- a/SuperSocket.sln +++ b/SuperSocket.sln @@ -7,8 +7,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{DDA4741E-097 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Primitives", "src\SuperSocket.Primitives\SuperSocket.Primitives.csproj", "{A1317CCC-70F4-4F32-84DE-2AAF68E346D2}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Channel", "src\SuperSocket.Channel\SuperSocket.Channel.csproj", "{829C73CC-6166-4DF8-9FAF-18B55E15D5B2}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.ProtoBase", "src\SuperSocket.ProtoBase\SuperSocket.ProtoBase.csproj", "{7EE705BE-5645-451B-B5A2-50408F63A222}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Server", "src\SuperSocket.Server\SuperSocket.Server.csproj", "{0A6AD2CC-E14C-43FF-BDA8-0F6DD0290CA3}" @@ -25,8 +23,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.WebSocket", "sr EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.WebSocket.Server", "src\SuperSocket.WebSocket.Server\SuperSocket.WebSocket.Server.csproj", "{4E9A4A13-0F74-4325-803A-351447336859}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.SessionContainer", "src\SuperSocket.SessionContainer\SuperSocket.SessionContainer.csproj", "{46618C5F-987D-40B3-B882-1C4895001D61}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Client.Proxy", "src\SuperSocket.Client.Proxy\SuperSocket.Client.Proxy.csproj", "{62BC2056-F454-4E7A-86E5-1C2E866145AB}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Tests.Command", "test\SuperSocket.Tests.Command\SuperSocket.Tests.Command.csproj", "{A68F2204-5021-4657-AACC-971FEBA385EB}" @@ -37,7 +33,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Benchmarks", "t EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.Udp", "src\SuperSocket.Udp\SuperSocket.Udp.csproj", "{695AA5D6-62C6-4D7E-8023-967CF134E26C}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SuperSocket.GZip", "src\SuperSocket.GZip\SuperSocket.GZip.csproj", "{DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Server.Abstractions", "src\SuperSocket.Server.Abstractions\SuperSocket.Server.Abstractions.csproj", "{8454E8D5-777D-46CB-B050-76C5119B624B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Connection", "src\SuperSocket.Connection\SuperSocket.Connection.csproj", "{FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -61,18 +59,6 @@ Global {A1317CCC-70F4-4F32-84DE-2AAF68E346D2}.Release|x64.Build.0 = Release|Any CPU {A1317CCC-70F4-4F32-84DE-2AAF68E346D2}.Release|x86.ActiveCfg = Release|Any CPU {A1317CCC-70F4-4F32-84DE-2AAF68E346D2}.Release|x86.Build.0 = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|x64.ActiveCfg = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|x64.Build.0 = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|x86.ActiveCfg = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Debug|x86.Build.0 = Debug|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|Any CPU.Build.0 = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|x64.ActiveCfg = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|x64.Build.0 = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|x86.ActiveCfg = Release|Any CPU - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2}.Release|x86.Build.0 = Release|Any CPU {7EE705BE-5645-451B-B5A2-50408F63A222}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7EE705BE-5645-451B-B5A2-50408F63A222}.Debug|Any CPU.Build.0 = Debug|Any CPU {7EE705BE-5645-451B-B5A2-50408F63A222}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -157,18 +143,6 @@ Global {4E9A4A13-0F74-4325-803A-351447336859}.Release|x64.Build.0 = Release|Any CPU {4E9A4A13-0F74-4325-803A-351447336859}.Release|x86.ActiveCfg = Release|Any CPU {4E9A4A13-0F74-4325-803A-351447336859}.Release|x86.Build.0 = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|Any CPU.Build.0 = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|x64.ActiveCfg = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|x64.Build.0 = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|x86.ActiveCfg = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Debug|x86.Build.0 = Debug|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|Any CPU.ActiveCfg = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|Any CPU.Build.0 = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|x64.ActiveCfg = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|x64.Build.0 = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|x86.ActiveCfg = Release|Any CPU - {46618C5F-987D-40B3-B882-1C4895001D61}.Release|x86.Build.0 = Release|Any CPU {62BC2056-F454-4E7A-86E5-1C2E866145AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {62BC2056-F454-4E7A-86E5-1C2E866145AB}.Debug|Any CPU.Build.0 = Debug|Any CPU {62BC2056-F454-4E7A-86E5-1C2E866145AB}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -229,25 +203,36 @@ Global {695AA5D6-62C6-4D7E-8023-967CF134E26C}.Release|x64.Build.0 = Release|Any CPU {695AA5D6-62C6-4D7E-8023-967CF134E26C}.Release|x86.ActiveCfg = Release|Any CPU {695AA5D6-62C6-4D7E-8023-967CF134E26C}.Release|x86.Build.0 = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|x64.ActiveCfg = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|x64.Build.0 = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|x86.ActiveCfg = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Debug|x86.Build.0 = Debug|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|Any CPU.Build.0 = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|x64.ActiveCfg = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|x64.Build.0 = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|x86.ActiveCfg = Release|Any CPU - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F}.Release|x86.Build.0 = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|x64.ActiveCfg = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|x64.Build.0 = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|x86.ActiveCfg = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Debug|x86.Build.0 = Debug|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|Any CPU.Build.0 = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|x64.ActiveCfg = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|x64.Build.0 = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|x86.ActiveCfg = Release|Any CPU + {8454E8D5-777D-46CB-B050-76C5119B624B}.Release|x86.Build.0 = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|x64.ActiveCfg = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|x64.Build.0 = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|x86.ActiveCfg = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Debug|x86.Build.0 = Debug|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|Any CPU.Build.0 = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|x64.ActiveCfg = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|x64.Build.0 = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|x86.ActiveCfg = Release|Any CPU + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {A1317CCC-70F4-4F32-84DE-2AAF68E346D2} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} - {829C73CC-6166-4DF8-9FAF-18B55E15D5B2} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {7EE705BE-5645-451B-B5A2-50408F63A222} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {0A6AD2CC-E14C-43FF-BDA8-0F6DD0290CA3} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {FF75EEF9-2CB9-4E6F-A5A8-38F2199B4B56} = {4040EEC4-6FB7-47B1-B487-23E043A0F52F} @@ -255,13 +240,13 @@ Global {E1C29FC7-8A20-4811-94A5-0B80F1632E9D} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {D648690B-1D08-4B8D-A299-681938B128F2} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {4E9A4A13-0F74-4325-803A-351447336859} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} - {46618C5F-987D-40B3-B882-1C4895001D61} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {62BC2056-F454-4E7A-86E5-1C2E866145AB} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {A68F2204-5021-4657-AACC-971FEBA385EB} = {4040EEC4-6FB7-47B1-B487-23E043A0F52F} {1C563726-BBB3-4D2D-B426-6C1A72A5B959} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} {4DFB226C-2D1A-4346-B984-468A523209AF} = {4040EEC4-6FB7-47B1-B487-23E043A0F52F} {695AA5D6-62C6-4D7E-8023-967CF134E26C} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} - {DEF97D4F-01BC-49E5-8B8B-D23C6652F80F} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} + {8454E8D5-777D-46CB-B050-76C5119B624B} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} + {FC2B529F-4AF4-4C39-BC4F-A3836CC7B37C} = {DDA4741E-097F-40C3-A252-2E1E3476C1A7} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {ADB30AA2-A848-4CB3-8A20-488C80F1BA9E} diff --git a/samples/AspNetSample/Program.cs b/samples/AspNetSample/Program.cs index 7e7d75aa7..b1eef1db8 100644 --- a/samples/AspNetSample/Program.cs +++ b/samples/AspNetSample/Program.cs @@ -2,6 +2,9 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using SuperSocket; +using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.ProtoBase; using System.Text; diff --git a/samples/CommandServer/ADD.cs b/samples/CommandServer/ADD.cs index 348ea8940..2609a44a8 100644 --- a/samples/CommandServer/ADD.cs +++ b/samples/CommandServer/ADD.cs @@ -2,6 +2,7 @@ using System.Text; using System.Threading.Tasks; using SuperSocket; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Command; using SuperSocket.ProtoBase; diff --git a/samples/CommandServer/MULT.cs b/samples/CommandServer/MULT.cs index 299b988e6..1dc791516 100644 --- a/samples/CommandServer/MULT.cs +++ b/samples/CommandServer/MULT.cs @@ -2,6 +2,7 @@ using System.Text; using System.Threading.Tasks; using SuperSocket; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Command; using SuperSocket.ProtoBase; diff --git a/samples/CommandServer/Program.cs b/samples/CommandServer/Program.cs index b169b066e..6b419630b 100644 --- a/samples/CommandServer/Program.cs +++ b/samples/CommandServer/Program.cs @@ -5,6 +5,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; +using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Command; using SuperSocket.ProtoBase; diff --git a/samples/CommandServer/SUB.cs b/samples/CommandServer/SUB.cs index c5116afdc..a97ba1c4a 100644 --- a/samples/CommandServer/SUB.cs +++ b/samples/CommandServer/SUB.cs @@ -2,6 +2,7 @@ using System.Text; using System.Threading.Tasks; using SuperSocket; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Command; using SuperSocket.ProtoBase; diff --git a/samples/ConfigSample/Program.cs b/samples/ConfigSample/Program.cs index 8a016afcc..ad8d1d9b3 100644 --- a/samples/ConfigSample/Program.cs +++ b/samples/ConfigSample/Program.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; +using SuperSocket.Server.Host; using SuperSocket.ProtoBase; namespace ConfigSample diff --git a/samples/CustomProtocol/Program.cs b/samples/CustomProtocol/Program.cs index e3d9d6738..da8d9525c 100644 --- a/samples/CustomProtocol/Program.cs +++ b/samples/CustomProtocol/Program.cs @@ -4,6 +4,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; +using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Host; using SuperSocket.ProtoBase; namespace CustomProtocol diff --git a/samples/EchoServer/Program.cs b/samples/EchoServer/Program.cs index e35520d8b..20f98d7c5 100644 --- a/samples/EchoServer/Program.cs +++ b/samples/EchoServer/Program.cs @@ -5,6 +5,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; +using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Host; using SuperSocket.ProtoBase; namespace EchoServer diff --git a/samples/WebSocketPushServer/Program.cs b/samples/WebSocketPushServer/Program.cs index 8d04dc754..14b6b1323 100644 --- a/samples/WebSocketPushServer/Program.cs +++ b/samples/WebSocketPushServer/Program.cs @@ -6,6 +6,11 @@ using Microsoft.Extensions.Logging; using SuperSocket; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; +using SuperSocket.Server.Host; using SuperSocket.WebSocket.Server; namespace WebSocketPushServer diff --git a/samples/WebSocketPushServer/PushSession.cs b/samples/WebSocketPushServer/PushSession.cs index 85c26c698..400778da9 100644 --- a/samples/WebSocketPushServer/PushSession.cs +++ b/samples/WebSocketPushServer/PushSession.cs @@ -6,7 +6,7 @@ using SuperSocket; using SuperSocket.Server; using SuperSocket.WebSocket.Server; -using SuperSocket.SessionContainer; +using SuperSocket.Server.Abstractions.Session; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; diff --git a/samples/WebSocketPushServer/ServerPushMiddleware.cs b/samples/WebSocketPushServer/ServerPushMiddleware.cs index e4c1c1d44..591b08cba 100644 --- a/samples/WebSocketPushServer/ServerPushMiddleware.cs +++ b/samples/WebSocketPushServer/ServerPushMiddleware.cs @@ -5,8 +5,10 @@ using System.Linq; using SuperSocket; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; using SuperSocket.WebSocket.Server; -using SuperSocket.SessionContainer; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; diff --git a/samples/WebSocketPushServer/WebSocketPushServer.csproj b/samples/WebSocketPushServer/WebSocketPushServer.csproj index 3de3f999e..a1cf9cbe9 100644 --- a/samples/WebSocketPushServer/WebSocketPushServer.csproj +++ b/samples/WebSocketPushServer/WebSocketPushServer.csproj @@ -4,8 +4,7 @@ $(SamplesTargetFrameworks) - - + diff --git a/src/SuperSocket.Channel/SslStreamPipeChannel.cs b/src/SuperSocket.Channel/SslStreamPipeChannel.cs deleted file mode 100644 index 9cb7223dc..000000000 --- a/src/SuperSocket.Channel/SslStreamPipeChannel.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Net; -using SuperSocket.ProtoBase; -using System.Net.Security; -using System.Security.Cryptography.X509Certificates; - -namespace SuperSocket.Channel -{ - public class SslStreamPipeChannel : StreamPipeChannel, IChannelWithRemoteCertificate - { - public SslStreamPipeChannel(SslStream stream, EndPoint remoteEndPoint, IPipelineFilter pipelineFilter, ChannelOptions options) - : this(stream, remoteEndPoint, null, pipelineFilter, options) - { - } - - public SslStreamPipeChannel(SslStream stream, EndPoint remoteEndPoint, EndPoint localEndPoint, IPipelineFilter pipelineFilter, ChannelOptions options) - : base(stream, remoteEndPoint, localEndPoint, pipelineFilter, options) - { - if (stream.IsAuthenticated || stream.IsMutuallyAuthenticated) - { - RemoteCertificate = stream.RemoteCertificate; - } - } - - public X509Certificate RemoteCertificate { get; } - } -} diff --git a/src/SuperSocket.Client.Proxy/HttpConnector.cs b/src/SuperSocket.Client.Proxy/HttpConnector.cs index d4f34b27a..12011e254 100644 --- a/src/SuperSocket.Client.Proxy/HttpConnector.cs +++ b/src/SuperSocket.Client.Proxy/HttpConnector.cs @@ -3,7 +3,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Client.Proxy @@ -33,7 +33,7 @@ protected override async ValueTask ConnectProxyAsync(EndPoint remo { var encoding = Encoding.ASCII; var request = string.Empty; - var channel = state.CreateChannel(new LinePipelineFilter(encoding), new ChannelOptions { ReadAsDemand = true }); + var channel = state.CreateConnection(new LinePipelineFilter(encoding), new ConnectionOptions { ReadAsDemand = true }); channel.Start(); diff --git a/src/SuperSocket.Client.Proxy/ProxyConnectorBase.cs b/src/SuperSocket.Client.Proxy/ProxyConnectorBase.cs index 502e16b89..a9921fcc7 100644 --- a/src/SuperSocket.Client.Proxy/ProxyConnectorBase.cs +++ b/src/SuperSocket.Client.Proxy/ProxyConnectorBase.cs @@ -5,7 +5,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.Client; using SuperSocket.ProtoBase; diff --git a/src/SuperSocket.Client.Proxy/Socks5Connector.cs b/src/SuperSocket.Client.Proxy/Socks5Connector.cs index 94453be27..a6fa311ab 100644 --- a/src/SuperSocket.Client.Proxy/Socks5Connector.cs +++ b/src/SuperSocket.Client.Proxy/Socks5Connector.cs @@ -6,7 +6,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -39,19 +39,19 @@ public Socks5Connector(EndPoint proxyEndPoint, string username, string password) protected override async ValueTask ConnectProxyAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { - var channel = state.CreateChannel(new Socks5AuthPipelineFilter(), new ChannelOptions { ReadAsDemand = true }); + var connection = state.CreateConnection(new Socks5AuthPipelineFilter(), new ConnectionOptions { ReadAsDemand = true }); - channel.Start(); + connection.Start(); - var packStream = channel.GetPackageStream(); + var packStream = connection.GetPackageStream(); - await channel.SendAsync(_authenHandshakeRequest); + await connection.SendAsync(_authenHandshakeRequest); var response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.Handshake, out string errorMessage)) { - await channel.CloseAsync(CloseReason.ProtocolError); + await connection.CloseAsync(CloseReason.ProtocolError); return new ConnectState { @@ -64,13 +64,13 @@ protected override async ValueTask ConnectProxyAsync(EndPoint remo { var passAuthenRequest = GetPassAuthenBytes(); - await channel.SendAsync(passAuthenRequest); + await connection.SendAsync(passAuthenRequest); response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.AuthUserName, out errorMessage)) { - await channel.CloseAsync(CloseReason.ProtocolError); + await connection.CloseAsync(CloseReason.ProtocolError); return new ConnectState { @@ -82,13 +82,13 @@ protected override async ValueTask ConnectProxyAsync(EndPoint remo var endPointRequest = GetEndPointBytes(remoteEndPoint); - await channel.SendAsync(endPointRequest); + await connection.SendAsync(endPointRequest); response = await packStream.ReceiveAsync(); if (!HandleResponse(response, Socket5ResponseType.AuthEndPoint, out errorMessage)) { - await channel.CloseAsync(CloseReason.ProtocolError); + await connection.CloseAsync(CloseReason.ProtocolError); return new ConnectState { @@ -97,7 +97,7 @@ protected override async ValueTask ConnectProxyAsync(EndPoint remo }; } - await channel.DetachAsync(); + await connection.DetachAsync(); return state; } diff --git a/src/SuperSocket.Client/ConnectState.cs b/src/SuperSocket.Client/ConnectState.cs index 5b93d7368..39d3a162c 100644 --- a/src/SuperSocket.Client/ConnectState.cs +++ b/src/SuperSocket.Client/ConnectState.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Net.Sockets; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Client @@ -30,7 +30,7 @@ private ConnectState(bool cancelled) public static readonly ConnectState CancelledState = new ConnectState(false); - public IChannel CreateChannel(IPipelineFilter pipelineFilter, ChannelOptions channelOptions) + public IConnection CreateConnection(IPipelineFilter pipelineFilter, ConnectionOptions connectionOptions) where TReceivePackage : class { var stream = this.Stream; @@ -38,11 +38,11 @@ public IChannel CreateChannel(IPipelineFilter< if (stream != null) { - return new StreamPipeChannel(stream , socket.RemoteEndPoint, socket.LocalEndPoint, pipelineFilter, channelOptions); + return new StreamPipeConnection(stream , socket.RemoteEndPoint, socket.LocalEndPoint, pipelineFilter, connectionOptions); } else { - return new TcpPipeChannel(socket, pipelineFilter, channelOptions); + return new TcpPipeConnection(socket, pipelineFilter, connectionOptions); } } } diff --git a/src/SuperSocket.Client/ConnectorBase.cs b/src/SuperSocket.Client/ConnectorBase.cs index c61e06251..646bb6c1d 100644 --- a/src/SuperSocket.Client/ConnectorBase.cs +++ b/src/SuperSocket.Client/ConnectorBase.cs @@ -6,19 +6,13 @@ namespace SuperSocket.Client { public abstract class ConnectorBase : IConnector { - public IConnector NextConnector { get; private set; } + public IConnector NextConnector { get; internal set; } public ConnectorBase() { } - public ConnectorBase(IConnector nextConnector) - : this() - { - NextConnector = nextConnector; - } - protected abstract ValueTask ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken); async ValueTask IConnector.ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) diff --git a/src/SuperSocket.Client/EasyClient.cs b/src/SuperSocket.Client/EasyClient.cs index 0f85d0999..1ae979110 100644 --- a/src/SuperSocket.Client/EasyClient.cs +++ b/src/SuperSocket.Client/EasyClient.cs @@ -8,8 +8,10 @@ using System.Security.Authentication; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; +using System.IO.Compression; +using System.Linq; namespace SuperSocket.Client @@ -26,12 +28,12 @@ protected EasyClient(IPackageEncoder packageEncoder) } public EasyClient(IPipelineFilter pipelineFilter, IPackageEncoder packageEncoder, ILogger logger = null) - : this(pipelineFilter, packageEncoder, new ChannelOptions { Logger = logger }) + : this(pipelineFilter, packageEncoder, new ConnectionOptions { Logger = logger }) { } - public EasyClient(IPipelineFilter pipelineFilter, IPackageEncoder packageEncoder, ChannelOptions options) + public EasyClient(IPipelineFilter pipelineFilter, IPackageEncoder packageEncoder, ConnectionOptions options) : base(pipelineFilter, options) { _packageEncoder = packageEncoder; @@ -53,11 +55,11 @@ public class EasyClient : IEasyClient { private IPipelineFilter _pipelineFilter; - protected IChannel Channel { get; private set; } + protected IConnection Connection { get; private set; } protected ILogger Logger { get; set; } - protected ChannelOptions Options { get; private set; } + protected ConnectionOptions Options { get; private set; } IAsyncEnumerator _packageStream; @@ -67,6 +69,8 @@ public class EasyClient : IEasyClient public SecurityOptions Security { get; set; } + public CompressionLevel CompressionLevel { get; set; } = CompressionLevel.NoCompression; + protected EasyClient() { @@ -79,12 +83,12 @@ public EasyClient(IPipelineFilter pipelineFilter) } public EasyClient(IPipelineFilter pipelineFilter, ILogger logger) - : this(pipelineFilter, new ChannelOptions { Logger = logger }) + : this(pipelineFilter, new ConnectionOptions { Logger = logger }) { } - public EasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) + public EasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) { if (pipelineFilter == null) throw new ArgumentNullException(nameof(pipelineFilter)); @@ -104,15 +108,41 @@ public virtual IEasyClient AsClient() protected virtual IConnector GetConnector() { + var connectors = new List(); + + connectors.Add(new SocketConnector(LocalEndPoint)); + var security = Security; if (security != null) { if (security.EnabledSslProtocols != SslProtocols.None) - return new SocketConnector(LocalEndPoint, new SslStreamConnector(security)); + connectors.Add(new SslStreamConnector(security)); + } + + if (CompressionLevel != CompressionLevel.NoCompression) + { + connectors.Add(new GZipConnector(CompressionLevel)); + } + + return BuildConnectors(connectors); + } + + protected IConnector BuildConnectors(IEnumerable connectors) + { + var prevConnector = default(ConnectorBase); + + foreach (var connector in connectors) + { + if (prevConnector != null) + { + prevConnector.NextConnector = connector; + } + + prevConnector = connector as ConnectorBase; } - return new SocketConnector(LocalEndPoint); + return connectors.First(); } ValueTask IEasyClient.ConnectAsync(EndPoint remoteEndPoint, CancellationToken cancellationToken) @@ -142,8 +172,8 @@ protected virtual async ValueTask ConnectAsync(EndPoint remoteEndPoint, Ca if (socket == null) throw new Exception("Socket is null."); - var channelOptions = Options; - SetupChannel(state.CreateChannel(_pipelineFilter, channelOptions)); + var connectionOptions = Options; + SetupConnection(state.CreateConnection(_pipelineFilter, connectionOptions)); return true; } @@ -161,14 +191,14 @@ public void AsUdp(IPEndPoint remoteEndPoint, ArrayPool bufferPool = null, // bind the local endpoint socket.Bind(localEndPoint); - var channel = new UdpPipeChannel(socket, _pipelineFilter, this.Options, remoteEndPoint); + var connection = new UdpPipeConnection(socket, _pipelineFilter, this.Options, remoteEndPoint); - SetupChannel(channel); + SetupConnection(connection); - UdpReceive(socket, channel, bufferPool, bufferSize); + UdpReceive(socket, connection, bufferPool, bufferSize); } - private async void UdpReceive(Socket socket, UdpPipeChannel channel, ArrayPool bufferPool, int bufferSize) + private async void UdpReceive(Socket socket, UdpPipeConnection channel, ArrayPool bufferPool, int bufferSize) { if (bufferPool == null) bufferPool = ArrayPool.Shared; @@ -204,12 +234,12 @@ private async void UdpReceive(Socket socket, UdpPipeChannel cha } } - protected virtual void SetupChannel(IChannel channel) + protected virtual void SetupConnection(IConnection connection) { - channel.Closed += OnChannelClosed; - channel.Start(); - _packageStream = channel.GetPackageStream(); - Channel = channel; + connection.Closed += OnConnectionClosed; + connection.Start(); + _packageStream = connection.GetPackageStream(); + Connection = connection; } ValueTask IEasyClient.ReceiveAsync() @@ -228,7 +258,7 @@ protected virtual async ValueTask ReceiveAsync() if (p != null) return p; - OnClosed(Channel, EventArgs.Empty); + OnClosed(Connection, EventArgs.Empty); return null; } @@ -269,9 +299,9 @@ protected virtual async ValueTask OnPackageReceived(TReceivePackage package) } } - private void OnChannelClosed(object sender, EventArgs e) + private void OnConnectionClosed(object sender, EventArgs e) { - Channel.Closed -= OnChannelClosed; + Connection.Closed -= OnConnectionClosed; OnClosed(this, e); } @@ -305,7 +335,7 @@ ValueTask IEasyClient.SendAsync(ReadOnlyMemory data) protected virtual async ValueTask SendAsync(ReadOnlyMemory data) { - await Channel.SendAsync(data); + await Connection.SendAsync(data); } ValueTask IEasyClient.SendAsync(IPackageEncoder packageEncoder, TSendPackage package) @@ -315,14 +345,14 @@ ValueTask IEasyClient.SendAsync(IPackageEncoder(IPackageEncoder packageEncoder, TSendPackage package) { - await Channel.SendAsync(packageEncoder, package); + await Connection.SendAsync(packageEncoder, package); } public event EventHandler Closed; public virtual async ValueTask CloseAsync() { - await Channel.CloseAsync(CloseReason.LocalClosing); + await Connection.CloseAsync(CloseReason.LocalClosing); OnClosed(this, EventArgs.Empty); } } diff --git a/src/SuperSocket.GZip/GZipConnector.cs b/src/SuperSocket.Client/GZipConnector.cs similarity index 68% rename from src/SuperSocket.GZip/GZipConnector.cs rename to src/SuperSocket.Client/GZipConnector.cs index 5821335ae..4a6841f21 100644 --- a/src/SuperSocket.GZip/GZipConnector.cs +++ b/src/SuperSocket.Client/GZipConnector.cs @@ -1,24 +1,24 @@ -using SuperSocket.Client; -using System; +using System; using System.Collections.Generic; +using System.IO.Compression; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; +using SuperSocket.Connection; -namespace SuperSocket.GZip +namespace SuperSocket.Client { public class GZipConnector : ConnectorBase { - public GZipConnector(IConnector nextConnector) - : base(nextConnector) - { - } - public GZipConnector() + private CompressionLevel _compressionLevel; + + public GZipConnector(CompressionLevel compressionLevel) : base() { + _compressionLevel = compressionLevel; } protected override ValueTask ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) @@ -39,8 +39,12 @@ protected override ValueTask ConnectAsync(EndPoint remoteEndPoint, try { - var gzipStream = new GZipReadWriteStream(stream, true); - state.Stream = gzipStream; + var pipeStream = new ReadWriteDelegateStream( + stream, + new GZipStream(stream, CompressionMode.Decompress), + new GZipStream(stream, CompressionMode.Compress)); + + state.Stream = pipeStream; return new ValueTask(state); } catch (Exception e) diff --git a/src/SuperSocket.Client/SocketConnector.cs b/src/SuperSocket.Client/SocketConnector.cs index bd8dfac06..7457b4be4 100644 --- a/src/SuperSocket.Client/SocketConnector.cs +++ b/src/SuperSocket.Client/SocketConnector.cs @@ -16,24 +16,12 @@ public SocketConnector() } - public SocketConnector(IConnector nextConnector) - : base(nextConnector) - { - - } - public SocketConnector(IPEndPoint localEndPoint) : base() { LocalEndPoint = localEndPoint; } - public SocketConnector(IPEndPoint localEndPoint, IConnector nextConnector) - : base(nextConnector) - { - LocalEndPoint = localEndPoint; - } - protected override async ValueTask ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { var socket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); diff --git a/src/SuperSocket.Client/SslStreamConnector.cs b/src/SuperSocket.Client/SslStreamConnector.cs index 7a74dff4e..dbf119f22 100644 --- a/src/SuperSocket.Client/SslStreamConnector.cs +++ b/src/SuperSocket.Client/SslStreamConnector.cs @@ -19,12 +19,6 @@ public SslStreamConnector(SslClientAuthenticationOptions options) Options = options; } - public SslStreamConnector(SslClientAuthenticationOptions options, IConnector nextConnector) - : base(nextConnector) - { - Options = options; - } - protected override async ValueTask ConnectAsync(EndPoint remoteEndPoint, ConnectState state, CancellationToken cancellationToken) { var targetHost = Options.TargetHost; diff --git a/src/SuperSocket.Client/SuperSocket.Client.csproj b/src/SuperSocket.Client/SuperSocket.Client.csproj index 32a4b4465..c4ad6eed2 100644 --- a/src/SuperSocket.Client/SuperSocket.Client.csproj +++ b/src/SuperSocket.Client/SuperSocket.Client.csproj @@ -6,7 +6,7 @@ - + diff --git a/src/SuperSocket.Command/CommandExecutingContext.cs b/src/SuperSocket.Command/CommandExecutingContext.cs index e24c296e7..a8648a43a 100644 --- a/src/SuperSocket.Command/CommandExecutingContext.cs +++ b/src/SuperSocket.Command/CommandExecutingContext.cs @@ -1,4 +1,5 @@ using System; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Command { diff --git a/src/SuperSocket.Command/CommandMiddleware.cs b/src/SuperSocket.Command/CommandMiddleware.cs index 27e4b08f5..ca86bbbb9 100644 --- a/src/SuperSocket.Command/CommandMiddleware.cs +++ b/src/SuperSocket.Command/CommandMiddleware.cs @@ -6,6 +6,9 @@ using Microsoft.Extensions.Options; using Microsoft.Extensions.DependencyInjection; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; using Microsoft.Extensions.Logging; namespace SuperSocket.Command diff --git a/src/SuperSocket.Command/CommandMiddlewareExtensions.cs b/src/SuperSocket.Command/CommandMiddlewareExtensions.cs index b067e6381..1ead81e12 100644 --- a/src/SuperSocket.Command/CommandMiddlewareExtensions.cs +++ b/src/SuperSocket.Command/CommandMiddlewareExtensions.cs @@ -1,10 +1,11 @@ using System; using System.Linq; using System.Collections.Generic; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using SuperSocket.Command; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Middleware; namespace SuperSocket { diff --git a/src/SuperSocket.Command/CommandOptions.cs b/src/SuperSocket.Command/CommandOptions.cs index 39510b729..1d759292c 100644 --- a/src/SuperSocket.Command/CommandOptions.cs +++ b/src/SuperSocket.Command/CommandOptions.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Collections.Generic; using System.Reflection; -using System.Threading.Tasks; namespace SuperSocket.Command { diff --git a/src/SuperSocket.Command/CommandWrap.cs b/src/SuperSocket.Command/CommandWrap.cs index 3fbfb28ff..798230176 100644 --- a/src/SuperSocket.Command/CommandWrap.cs +++ b/src/SuperSocket.Command/CommandWrap.cs @@ -1,8 +1,7 @@ using System; using System.Threading.Tasks; -using System.Text.Json; -using SuperSocket.ProtoBase; using Microsoft.Extensions.DependencyInjection; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Command { diff --git a/src/SuperSocket.Command/ICommand.cs b/src/SuperSocket.Command/ICommand.cs index 8e032e5bd..b56a9a9b6 100644 --- a/src/SuperSocket.Command/ICommand.cs +++ b/src/SuperSocket.Command/ICommand.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Command { diff --git a/src/SuperSocket.Command/JsonCommand.cs b/src/SuperSocket.Command/JsonCommand.cs index df37d0349..ad225f418 100644 --- a/src/SuperSocket.Command/JsonCommand.cs +++ b/src/SuperSocket.Command/JsonCommand.cs @@ -1,6 +1,7 @@ using System.Threading.Tasks; using System.Text.Json; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Command { diff --git a/src/SuperSocket.Command/SuperSocket.Command.csproj b/src/SuperSocket.Command/SuperSocket.Command.csproj index 81188ffe3..614db2e33 100644 --- a/src/SuperSocket.Command/SuperSocket.Command.csproj +++ b/src/SuperSocket.Command/SuperSocket.Command.csproj @@ -3,11 +3,14 @@ SuperSocket command pattern library which allow you to handle requests with commands. - + + + + diff --git a/src/SuperSocket.Channel/CloseReason.cs b/src/SuperSocket.Connection/CloseReason.cs similarity index 88% rename from src/SuperSocket.Channel/CloseReason.cs rename to src/SuperSocket.Connection/CloseReason.cs index be988764a..4b4c3eb44 100644 --- a/src/SuperSocket.Channel/CloseReason.cs +++ b/src/SuperSocket.Connection/CloseReason.cs @@ -1,11 +1,6 @@ using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { public enum CloseReason { diff --git a/src/SuperSocket.Channel/ChannelBase.cs b/src/SuperSocket.Connection/ConnectionBase.cs similarity index 89% rename from src/SuperSocket.Channel/ChannelBase.cs rename to src/SuperSocket.Connection/ConnectionBase.cs index eb6f7259d..59c739c76 100644 --- a/src/SuperSocket.Channel/ChannelBase.cs +++ b/src/SuperSocket.Connection/ConnectionBase.cs @@ -6,9 +6,9 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public abstract class ChannelBase : IChannel, IChannel + public abstract class ConnectionBase : IConnection, IConnection { public abstract void Start(); @@ -42,7 +42,7 @@ protected virtual void OnClosed() if (Interlocked.CompareExchange(ref Closed, null, closed) != closed) return; - var closeReason = CloseReason.HasValue ? CloseReason.Value : Channel.CloseReason.Unknown; + var closeReason = CloseReason.HasValue ? CloseReason.Value : Connection.CloseReason.Unknown; closed.Invoke(this, new CloseEventArgs(closeReason)); } diff --git a/src/SuperSocket.Connection/ConnectionExtensions.cs b/src/SuperSocket.Connection/ConnectionExtensions.cs new file mode 100644 index 000000000..b33711bdc --- /dev/null +++ b/src/SuperSocket.Connection/ConnectionExtensions.cs @@ -0,0 +1,20 @@ +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; + +namespace SuperSocket.Connection +{ + public static class ConnectionExtensions + { + public static X509Certificate GetRemoteCertificate(this IConnection connection) + { + if (connection is IStreamConnection streamConnection + && streamConnection.Stream is SslStream sslStream + && sslStream.IsAuthenticated) + { + return sslStream.RemoteCertificate; + } + + return null; + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Channel/ChannelOptions.cs b/src/SuperSocket.Connection/ConnectionOptions.cs similarity index 93% rename from src/SuperSocket.Channel/ChannelOptions.cs rename to src/SuperSocket.Connection/ConnectionOptions.cs index 98693a1ad..c08653c50 100644 --- a/src/SuperSocket.Channel/ChannelOptions.cs +++ b/src/SuperSocket.Connection/ConnectionOptions.cs @@ -4,9 +4,9 @@ using Microsoft.Extensions.Logging; using System.Collections.Specialized; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public class ChannelOptions + public class ConnectionOptions { // 1M by default public int MaxPackageLength { get; set; } = 1024 * 1024; diff --git a/src/SuperSocket.Channel/DefaultObjectPipe.cs b/src/SuperSocket.Connection/DefaultObjectPipe.cs similarity index 99% rename from src/SuperSocket.Channel/DefaultObjectPipe.cs rename to src/SuperSocket.Connection/DefaultObjectPipe.cs index 55a4622e7..d976ef646 100644 --- a/src/SuperSocket.Channel/DefaultObjectPipe.cs +++ b/src/SuperSocket.Connection/DefaultObjectPipe.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using System.Threading.Tasks.Sources; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { class DefaultObjectPipe : IObjectPipe, IValueTaskSource, IDisposable { diff --git a/src/SuperSocket.Channel/Extensions.cs b/src/SuperSocket.Connection/Extensions.cs similarity index 78% rename from src/SuperSocket.Channel/Extensions.cs rename to src/SuperSocket.Connection/Extensions.cs index 30dd80d06..81564b9c0 100644 --- a/src/SuperSocket.Channel/Extensions.cs +++ b/src/SuperSocket.Connection/Extensions.cs @@ -3,14 +3,14 @@ using System.Threading; using System.Threading.Tasks; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { public static class Extensions { - public static IAsyncEnumerator GetPackageStream(this IChannel channel) + public static IAsyncEnumerator GetPackageStream(this IConnection connection) where TPackageInfo : class { - return channel.RunAsync().GetAsyncEnumerator(); + return connection.RunAsync().GetAsyncEnumerator(); } public static async ValueTask ReceiveAsync(this IAsyncEnumerator packageStream) diff --git a/src/SuperSocket.Channel/IChannelWithRemoteCertificate.cs b/src/SuperSocket.Connection/IChannelWithRemoteCertificate.cs similarity index 58% rename from src/SuperSocket.Channel/IChannelWithRemoteCertificate.cs rename to src/SuperSocket.Connection/IChannelWithRemoteCertificate.cs index c8f962994..402f97304 100644 --- a/src/SuperSocket.Channel/IChannelWithRemoteCertificate.cs +++ b/src/SuperSocket.Connection/IChannelWithRemoteCertificate.cs @@ -1,8 +1,8 @@ using System.Security.Cryptography.X509Certificates; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public interface IChannelWithRemoteCertificate + public interface IConnectionWithRemoteCertificate { X509Certificate RemoteCertificate { get; } } diff --git a/src/SuperSocket.Channel/IChannel.cs b/src/SuperSocket.Connection/IConnection.cs similarity index 86% rename from src/SuperSocket.Channel/IChannel.cs rename to src/SuperSocket.Connection/IConnection.cs index 587b89533..ea02ecba0 100644 --- a/src/SuperSocket.Channel/IChannel.cs +++ b/src/SuperSocket.Connection/IConnection.cs @@ -5,9 +5,9 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public interface IChannel + public interface IConnection { void Start(); @@ -34,7 +34,7 @@ public interface IChannel CloseReason? CloseReason { get; } } - public interface IChannel : IChannel + public interface IConnection : IConnection { IAsyncEnumerable RunAsync(); } diff --git a/src/SuperSocket.Connection/IConnectionFactory.cs b/src/SuperSocket.Connection/IConnectionFactory.cs new file mode 100644 index 000000000..87d1838c2 --- /dev/null +++ b/src/SuperSocket.Connection/IConnectionFactory.cs @@ -0,0 +1,10 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace SuperSocket.Connection +{ + public interface IConnectionFactory + { + Task CreateConnection(object connection, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Channel/IChannelWithSessionIdentifier.cs b/src/SuperSocket.Connection/IConnectionWithSessionIdentifier.cs similarity index 73% rename from src/SuperSocket.Channel/IChannelWithSessionIdentifier.cs rename to src/SuperSocket.Connection/IConnectionWithSessionIdentifier.cs index 8c2d4df75..481b0a6e2 100644 --- a/src/SuperSocket.Channel/IChannelWithSessionIdentifier.cs +++ b/src/SuperSocket.Connection/IConnectionWithSessionIdentifier.cs @@ -6,9 +6,9 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public interface IChannelWithSessionIdentifier + public interface IConnectionWithSessionIdentifier { string SessionIdentifier { get; } } diff --git a/src/SuperSocket.Channel/IObjectPipe.cs b/src/SuperSocket.Connection/IObjectPipe.cs similarity index 93% rename from src/SuperSocket.Channel/IObjectPipe.cs rename to src/SuperSocket.Connection/IObjectPipe.cs index ddf98f01c..d495bc846 100644 --- a/src/SuperSocket.Channel/IObjectPipe.cs +++ b/src/SuperSocket.Connection/IObjectPipe.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { interface IObjectPipe { diff --git a/src/SuperSocket.Channel/IPipeChannel.cs b/src/SuperSocket.Connection/IPipeConnection.cs similarity index 75% rename from src/SuperSocket.Channel/IPipeChannel.cs rename to src/SuperSocket.Connection/IPipeConnection.cs index 912f41eb5..2a25feec6 100644 --- a/src/SuperSocket.Channel/IPipeChannel.cs +++ b/src/SuperSocket.Connection/IPipeConnection.cs @@ -3,9 +3,9 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public interface IPipeChannel + public interface IPipeConnection { Pipe In { get; } diff --git a/src/SuperSocket.Connection/IStreamConnection.cs b/src/SuperSocket.Connection/IStreamConnection.cs new file mode 100644 index 000000000..1a5459002 --- /dev/null +++ b/src/SuperSocket.Connection/IStreamConnection.cs @@ -0,0 +1,9 @@ +using System.IO; + +namespace SuperSocket.Connection +{ + internal interface IStreamConnection + { + Stream Stream { get; } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Channel/IVirtualChannel.cs b/src/SuperSocket.Connection/IVirtualConnection.cs similarity index 77% rename from src/SuperSocket.Channel/IVirtualChannel.cs rename to src/SuperSocket.Connection/IVirtualConnection.cs index aef18ca6f..eb1fd3d4c 100644 --- a/src/SuperSocket.Channel/IVirtualChannel.cs +++ b/src/SuperSocket.Connection/IVirtualConnection.cs @@ -6,9 +6,9 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public interface IVirtualChannel : IChannel + public interface IVirtualConnection : IConnection { ValueTask WritePipeDataAsync(Memory memory, CancellationToken cancellationToken); } diff --git a/src/SuperSocket.Connection/PipeConnection.cs b/src/SuperSocket.Connection/PipeConnection.cs new file mode 100644 index 000000000..bf4e035f2 --- /dev/null +++ b/src/SuperSocket.Connection/PipeConnection.cs @@ -0,0 +1,90 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using System.Net.Sockets; +using System.Buffers; +using System.Collections.Generic; +using SuperSocket.ProtoBase; +using System.IO.Pipelines; + +namespace SuperSocket.Connection +{ + public abstract class PipeConnection : PipeConnectionBase + { + public PipeConnection(IPipelineFilter pipelineFilter, ConnectionOptions options) + : base(pipelineFilter, options) + { + } + + protected override Task StartTask() + { + var pipeTask = base.StartTask(); + return Task.WhenAll(pipeTask, ProcessSends()); + } + + protected virtual async Task ProcessSends() + { + var output = Out.Reader; + + while (true) + { + var completed = await ProcessOutputRead(output).ConfigureAwait(false); + + if (completed) + { + break; + } + } + + output.Complete(); + } + + protected async ValueTask ProcessOutputRead(PipeReader reader) + { + var result = await reader.ReadAsync(CancellationToken.None).ConfigureAwait(false); + + var completed = result.IsCompleted; + + var buffer = result.Buffer; + var end = buffer.End; + + if (!buffer.IsEmpty) + { + try + { + await SendOverIOAsync(buffer, CancellationToken.None).ConfigureAwait(false); ; + LastActiveTime = DateTimeOffset.Now; + } + catch (Exception e) + { + // Cancel all the work in the channel if encounter an error during sending + Cancel(); + + if (!IsIgnorableException(e)) + OnError("Exception happened in SendAsync", e); + + return true; + } + } + + reader.AdvanceTo(end); + return completed; + } + + protected abstract ValueTask SendOverIOAsync(ReadOnlySequence buffer, CancellationToken cancellationToken); + + protected override bool IsIgnorableException(Exception e) + { + if (base.IsIgnorableException(e)) + return true; + + if (e is SocketException se) + { + if (se.IsIgnorableSocketException()) + return true; + } + + return false; + } + } +} diff --git a/src/SuperSocket.Channel/PipeChannel.cs b/src/SuperSocket.Connection/PipeConnectionBase.cs similarity index 83% rename from src/SuperSocket.Channel/PipeChannel.cs rename to src/SuperSocket.Connection/PipeConnectionBase.cs index d9c81d2c9..8fc02542b 100644 --- a/src/SuperSocket.Channel/PipeChannel.cs +++ b/src/SuperSocket.Connection/PipeConnectionBase.cs @@ -5,37 +5,36 @@ using System.IO.Pipelines; using System.Collections.Generic; using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; using Microsoft.Extensions.Logging; using SuperSocket.ProtoBase; - -[assembly: InternalsVisibleTo("Test")] -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public abstract partial class PipeChannel : ChannelBase, IChannel, IChannel, IPipeChannel + public abstract partial class PipeConnectionBase : ConnectionBase, IConnection, IConnection, IPipeConnection { private IPipelineFilter _pipelineFilter; + private bool _started = false; + private CancellationTokenSource _cts = new CancellationTokenSource(); protected SemaphoreSlim SendLock { get; } = new SemaphoreSlim(1, 1); protected Pipe Out { get; } - Pipe IPipeChannel.Out + Pipe IPipeConnection.Out { get { return Out; } } protected Pipe In { get; } - Pipe IPipeChannel.In + Pipe IPipeConnection.In { get { return In; } } - IPipelineFilter IPipeChannel.PipelineFilter + IPipelineFilter IPipeConnection.PipelineFilter { get { return _pipelineFilter; } } @@ -44,15 +43,13 @@ IPipelineFilter IPipeChannel.PipelineFilter protected ILogger Logger { get; } - protected ChannelOptions Options { get; } - - private Task _readsTask; + protected ConnectionOptions Options { get; } - private Task _sendsTask; + private Task _pipeTask; private bool _isDetaching = false; - protected PipeChannel(IPipelineFilter pipelineFilter, ChannelOptions options) + protected PipeConnectionBase(IPipelineFilter pipelineFilter, ConnectionOptions options) { _pipelineFilter = pipelineFilter; @@ -69,11 +66,16 @@ protected PipeChannel(IPipelineFilter pipelineFilter, ChannelOptio public override void Start() { - _readsTask = ProcessReads(_cts.Token); - _sendsTask = ProcessSends(); + _pipeTask = StartTask(); + _started = true; WaitHandleClosing(); } + protected virtual Task StartTask() + { + return ProcessReads(_cts.Token); + } + private async void WaitHandleClosing() { await HandleClosing().ConfigureAwait(false); @@ -81,8 +83,8 @@ private async void WaitHandleClosing() public async override IAsyncEnumerable RunAsync() { - if (_readsTask == null || _sendsTask == null) - throw new Exception("The channel has not been started yet."); + if (!_started) + throw new Exception("The connection has not been started yet."); while (!_cts.IsCancellationRequested) { @@ -103,7 +105,7 @@ private async ValueTask HandleClosing() { try { - await Task.WhenAll(_readsTask, _sendsTask).ConfigureAwait(false); + await _pipeTask.ConfigureAwait(false); } catch (OperationCanceledException) { @@ -182,7 +184,7 @@ protected virtual async Task FillPipeAsync(PipeWriter writer, CancellationToken if (bytesRead == 0) { if (!CloseReason.HasValue) - CloseReason = Channel.CloseReason.RemoteClosing; + CloseReason = Connection.CloseReason.RemoteClosing; break; } @@ -202,12 +204,12 @@ protected virtual async Task FillPipeAsync(PipeWriter writer, CancellationToken if (!CloseReason.HasValue) { CloseReason = cancellationToken.IsCancellationRequested - ? Channel.CloseReason.LocalClosing : Channel.CloseReason.SocketError; + ? Connection.CloseReason.LocalClosing : Connection.CloseReason.SocketError; } } else if (!CloseReason.HasValue) { - CloseReason = Channel.CloseReason.RemoteClosing; + CloseReason = Connection.CloseReason.RemoteClosing; } break; @@ -251,57 +253,7 @@ protected virtual async Task ProcessReads(CancellationToken cancellationToken) await Task.WhenAll(reading, writing).ConfigureAwait(false); } - protected async ValueTask ProcessOutputRead(PipeReader reader) - { - var result = await reader.ReadAsync(CancellationToken.None).ConfigureAwait(false); - - var completed = result.IsCompleted; - - var buffer = result.Buffer; - var end = buffer.End; - - if (!buffer.IsEmpty) - { - try - { - await SendOverIOAsync(buffer, CancellationToken.None).ConfigureAwait(false);; - LastActiveTime = DateTimeOffset.Now; - } - catch (Exception e) - { - // Cancel all the work in the channel if encounter an error during sending - Cancel(); - - if (!IsIgnorableException(e)) - OnError("Exception happened in SendAsync", e); - - return true; - } - } - - reader.AdvanceTo(end); - return completed; - } - - protected virtual async Task ProcessSends() - { - var output = Out.Reader; - - while (true) - { - var completed = await ProcessOutputRead(output).ConfigureAwait(false); - - if (completed) - { - break; - } - } - - output.Complete(); - } - - - private void CheckChannelOpen() + private void CheckConnectionOpen() { if (this.IsClosed) { @@ -309,9 +261,6 @@ private void CheckChannelOpen() } } - protected abstract ValueTask SendOverIOAsync(ReadOnlySequence buffer, CancellationToken cancellationToken); - - public override async ValueTask SendAsync(ReadOnlyMemory buffer) { try @@ -329,7 +278,7 @@ public override async ValueTask SendAsync(ReadOnlyMemory buffer) private void WriteBuffer(PipeWriter writer, ReadOnlyMemory buffer) { - CheckChannelOpen(); + CheckConnectionOpen(); writer.Write(buffer.Span); } @@ -365,7 +314,7 @@ public override async ValueTask SendAsync(Action write) protected void WritePackageWithEncoder(IBufferWriter writer, IPackageEncoder packageEncoder, TPackage package) { - CheckChannelOpen(); + CheckConnectionOpen(); packageEncoder.Encode(writer, package); } @@ -429,7 +378,7 @@ protected async Task ReadPipeAsync(PipeReader reader, CancellationToken cancella { OnError("Protocol error", e); // close the connection if get a protocol error - CloseReason = Channel.CloseReason.ProtocolError; + CloseReason = Connection.CloseReason.ProtocolError; Close(); break; } @@ -487,7 +436,7 @@ private bool ReaderBuffer(ref ReadOnlySequence buffer, out SequencePositio if (maxPackageLength > 0 && len > maxPackageLength) { OnError($"Package cannot be larger than {maxPackageLength}."); - CloseReason = Channel.CloseReason.ProtocolError; + CloseReason = Connection.CloseReason.ProtocolError; // close the the connection directly Close(); return false; diff --git a/src/SuperSocket.GZip/GZipReadWriteStream.cs b/src/SuperSocket.Connection/ReadWriteDelegateStream.cs similarity index 89% rename from src/SuperSocket.GZip/GZipReadWriteStream.cs rename to src/SuperSocket.Connection/ReadWriteDelegateStream.cs index fc8c9bbbc..cb9002744 100644 --- a/src/SuperSocket.GZip/GZipReadWriteStream.cs +++ b/src/SuperSocket.Connection/ReadWriteDelegateStream.cs @@ -1,24 +1,21 @@ -using System; -using System.Buffers; -using System.Threading.Tasks; +using System; using System.IO; -using System.Net.Sockets; -using System.Net; using System.Threading; -using System.IO.Compression; +using System.Threading.Tasks; +using System.Buffers; -namespace SuperSocket.GZip +namespace SuperSocket.Connection { - public class GZipReadWriteStream : Stream + public class ReadWriteDelegateStream : Stream { public Stream BaseStream { get; } - GZipStream readStream = null; - GZipStream writeStream = null; - public GZipReadWriteStream(Stream stream, bool leaveOpen) + Stream readStream = null; + Stream writeStream = null; + public ReadWriteDelegateStream(Stream stream, Stream readStream, Stream writeStream) { - readStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen); - writeStream = new GZipStream(stream, CompressionMode.Compress, leaveOpen); - BaseStream = stream; + this.readStream = readStream; + this.writeStream = writeStream; + this.BaseStream = stream; } public override bool CanRead => true; @@ -144,4 +141,5 @@ public override void WriteByte(byte value) public override int ReadTimeout { get => BaseStream.ReadTimeout; set => BaseStream.ReadTimeout = value; } public override int WriteTimeout { get => BaseStream.WriteTimeout; set => BaseStream.WriteTimeout = value; } } + } \ No newline at end of file diff --git a/src/SuperSocket.Channel/RelayPipeChannel.cs b/src/SuperSocket.Connection/RelayPipeConnection.cs similarity index 78% rename from src/SuperSocket.Channel/RelayPipeChannel.cs rename to src/SuperSocket.Connection/RelayPipeConnection.cs index 4e32c320e..ef7618445 100644 --- a/src/SuperSocket.Channel/RelayPipeChannel.cs +++ b/src/SuperSocket.Connection/RelayPipeConnection.cs @@ -5,19 +5,19 @@ using System.IO.Pipelines; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public class RelayPipeChannel : PipeChannel + public class RelayPipeConnection : PipeConnection where TPackageInfo : class { - static ChannelOptions RebuildOptionsWithPipes(ChannelOptions options, Pipe pipeIn, Pipe pipeOut) + static ConnectionOptions RebuildOptionsWithPipes(ConnectionOptions options, Pipe pipeIn, Pipe pipeOut) { options.In = pipeIn; options.Out = pipeOut; return options; } - public RelayPipeChannel(IPipelineFilter pipelineFilter, ChannelOptions options, Pipe pipeIn, Pipe pipeOut) + public RelayPipeConnection(IPipelineFilter pipelineFilter, ConnectionOptions options, Pipe pipeIn, Pipe pipeOut) : base(pipelineFilter, RebuildOptionsWithPipes(options, pipeIn, pipeOut)) { diff --git a/src/SuperSocket.Channel/SocketExtensions.cs b/src/SuperSocket.Connection/SocketExtensions.cs similarity index 95% rename from src/SuperSocket.Channel/SocketExtensions.cs rename to src/SuperSocket.Connection/SocketExtensions.cs index cb49eb87a..35da2af48 100644 --- a/src/SuperSocket.Channel/SocketExtensions.cs +++ b/src/SuperSocket.Connection/SocketExtensions.cs @@ -3,7 +3,7 @@ using System.Net.Sockets; using System.Threading.Tasks; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { public static class SocketExtensions { diff --git a/src/SuperSocket.Channel/StreamPipeChannel.cs b/src/SuperSocket.Connection/StreamPipeConnection.cs similarity index 76% rename from src/SuperSocket.Channel/StreamPipeChannel.cs rename to src/SuperSocket.Connection/StreamPipeConnection.cs index e7f6e76b1..80e5c28dc 100644 --- a/src/SuperSocket.Channel/StreamPipeChannel.cs +++ b/src/SuperSocket.Connection/StreamPipeConnection.cs @@ -7,19 +7,19 @@ using System.Threading; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public class StreamPipeChannel : PipeChannel + public class StreamPipeConnection : PipeConnection, IStreamConnection { private Stream _stream; - public StreamPipeChannel(Stream stream, EndPoint remoteEndPoint, IPipelineFilter pipelineFilter, ChannelOptions options) + public StreamPipeConnection(Stream stream, EndPoint remoteEndPoint, IPipelineFilter pipelineFilter, ConnectionOptions options) : this(stream, remoteEndPoint, null, pipelineFilter, options) { } - public StreamPipeChannel(Stream stream, EndPoint remoteEndPoint, EndPoint localEndPoint, IPipelineFilter pipelineFilter, ChannelOptions options) + public StreamPipeConnection(Stream stream, EndPoint remoteEndPoint, EndPoint localEndPoint, IPipelineFilter pipelineFilter, ConnectionOptions options) : base(pipelineFilter, options) { _stream = stream; @@ -71,5 +71,10 @@ protected override bool IsIgnorableException(Exception e) return false; } + + Stream IStreamConnection.Stream + { + get { return _stream; } + } } } \ No newline at end of file diff --git a/src/SuperSocket.Channel/SuperSocket.Channel.csproj b/src/SuperSocket.Connection/SuperSocket.Connection.csproj similarity index 91% rename from src/SuperSocket.Channel/SuperSocket.Channel.csproj rename to src/SuperSocket.Connection/SuperSocket.Connection.csproj index a430e9930..813159a2c 100644 --- a/src/SuperSocket.Channel/SuperSocket.Channel.csproj +++ b/src/SuperSocket.Connection/SuperSocket.Connection.csproj @@ -1,6 +1,6 @@ - SuperSocket library to abstract underlying communications as channel with pipeline. + SuperSocket library to abstract underlying communications as connection with pipeline. diff --git a/src/SuperSocket.Channel/TcpPipeChannel.cs b/src/SuperSocket.Connection/TcpPipeConnection.cs similarity index 93% rename from src/SuperSocket.Channel/TcpPipeChannel.cs rename to src/SuperSocket.Connection/TcpPipeConnection.cs index 6b1a08924..06d29a175 100644 --- a/src/SuperSocket.Channel/TcpPipeChannel.cs +++ b/src/SuperSocket.Connection/TcpPipeConnection.cs @@ -6,16 +6,16 @@ using System.Collections.Generic; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public class TcpPipeChannel : PipeChannel + public class TcpPipeConnection : PipeConnection { private Socket _socket; private List> _segmentsForSend; - public TcpPipeChannel(Socket socket, IPipelineFilter pipelineFilter, ChannelOptions options) + public TcpPipeConnection(Socket socket, IPipelineFilter pipelineFilter, ConnectionOptions options) : base(pipelineFilter, options) { _socket = socket; diff --git a/src/SuperSocket.Channel/UdpPipeChannel.cs b/src/SuperSocket.Connection/UdpPipeConnection.cs similarity index 89% rename from src/SuperSocket.Channel/UdpPipeChannel.cs rename to src/SuperSocket.Connection/UdpPipeConnection.cs index 43e177982..d91631436 100644 --- a/src/SuperSocket.Channel/UdpPipeChannel.cs +++ b/src/SuperSocket.Connection/UdpPipeConnection.cs @@ -7,21 +7,21 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public class UdpPipeChannel : VirtualChannel, IChannelWithSessionIdentifier + public class UdpPipeConnection : VirtualConnection, IConnectionWithSessionIdentifier { private Socket _socket; private bool _enableSendingPipe; - public UdpPipeChannel(Socket socket, IPipelineFilter pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint) + public UdpPipeConnection(Socket socket, IPipelineFilter pipelineFilter, ConnectionOptions options, IPEndPoint remoteEndPoint) : this(socket, pipelineFilter, options, remoteEndPoint, $"{remoteEndPoint.Address}:{remoteEndPoint.Port}") { } - public UdpPipeChannel(Socket socket, IPipelineFilter pipelineFilter, ChannelOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier) + public UdpPipeConnection(Socket socket, IPipelineFilter pipelineFilter, ConnectionOptions options, IPEndPoint remoteEndPoint, string sessionIdentifier) : base(pipelineFilter, options) { _socket = socket; diff --git a/src/SuperSocket.Channel/VirtualChannel.cs b/src/SuperSocket.Connection/VirtualConnection.cs similarity index 72% rename from src/SuperSocket.Channel/VirtualChannel.cs rename to src/SuperSocket.Connection/VirtualConnection.cs index 5f6cfb81c..247fbeb3a 100644 --- a/src/SuperSocket.Channel/VirtualChannel.cs +++ b/src/SuperSocket.Connection/VirtualConnection.cs @@ -6,11 +6,11 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; -namespace SuperSocket.Channel +namespace SuperSocket.Connection { - public abstract class VirtualChannel : PipeChannel, IVirtualChannel + public abstract class VirtualConnection : PipeConnection, IVirtualConnection { - public VirtualChannel(IPipelineFilter pipelineFilter, ChannelOptions options) + public VirtualConnection(IPipelineFilter pipelineFilter, ConnectionOptions options) : base(pipelineFilter, options) { diff --git a/src/SuperSocket.GZip/GZipEasyClient.cs b/src/SuperSocket.GZip/GZipEasyClient.cs deleted file mode 100644 index 225b9366b..000000000 --- a/src/SuperSocket.GZip/GZipEasyClient.cs +++ /dev/null @@ -1,47 +0,0 @@ -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; -using SuperSocket.Client; -using SuperSocket.ProtoBase; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Security.Authentication; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace SuperSocket.GZip -{ - public class GZipEasyClient : EasyClient where TReceivePackage : class - { - public GZipEasyClient(IPipelineFilter pipelineFilter) : base(pipelineFilter) - { - } - - public GZipEasyClient(IPipelineFilter pipelineFilter, ILogger logger) : base(pipelineFilter, logger) - { - } - - public GZipEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) : base(pipelineFilter, options) - { - } - - protected GZipEasyClient() - { - } - protected override IConnector GetConnector() - { - var security = Security; - - if (security != null) - { - if (security.EnabledSslProtocols != SslProtocols.None) - return new SocketConnector(LocalEndPoint, new SslStreamConnector(security,new GZipConnector())); - } - - return new SocketConnector(LocalEndPoint,new GZipConnector()); - } - } -} diff --git a/src/SuperSocket.GZip/GZipTcpChannelCreatorFactory.cs b/src/SuperSocket.GZip/GZipTcpChannelCreatorFactory.cs deleted file mode 100644 index 7b8de39d6..000000000 --- a/src/SuperSocket.GZip/GZipTcpChannelCreatorFactory.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; -using SuperSocket.Server; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net.Security; -using System.Net.Sockets; -using System.Security.Authentication; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace SuperSocket.GZip -{ - public class GZipTcpChannelCreatorFactory : TcpChannelCreatorFactory, IChannelCreatorFactory - { - public GZipTcpChannelCreatorFactory(IServiceProvider serviceProvider) : base(serviceProvider) - { - } - - public new IChannelCreator CreateChannelCreator(ListenOptions options, ChannelOptions channelOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory) - { - var filterFactory = pipelineFilterFactory as IPipelineFilterFactory; - channelOptions.Logger = loggerFactory.CreateLogger(nameof(IChannel)); - - var channelFactoryLogger = loggerFactory.CreateLogger(nameof(TcpChannelCreator)); - - var channelFactory = new Func>(async (s) => - { - ApplySocketOptions(s, options, channelOptions, channelFactoryLogger); - - Stream stream = new NetworkStream(s, true); - if (options.Security != SslProtocols.None) - { - var authOptions = new SslServerAuthenticationOptions(); - - authOptions.EnabledSslProtocols = options.Security; - authOptions.ServerCertificate = options.CertificateOptions.Certificate; - authOptions.ClientCertificateRequired = options.CertificateOptions.ClientCertificateRequired; - - if (options.CertificateOptions.RemoteCertificateValidationCallback != null) - authOptions.RemoteCertificateValidationCallback = options.CertificateOptions.RemoteCertificateValidationCallback; - - var sslStream = new SslStream(stream, false); - await sslStream.AuthenticateAsServerAsync(authOptions, CancellationToken.None).ConfigureAwait(false); - - stream = sslStream; - } - stream = new GZipReadWriteStream(stream, true); - return new StreamPipeChannel(stream, s.RemoteEndPoint, s.LocalEndPoint, filterFactory.Create(s), channelOptions); - }); - - return new TcpChannelCreator(options, channelFactory, channelFactoryLogger); - } - } -} diff --git a/src/SuperSocket.GZip/HostBuilderExtensions.cs b/src/SuperSocket.GZip/HostBuilderExtensions.cs deleted file mode 100644 index 72f7d2253..000000000 --- a/src/SuperSocket.GZip/HostBuilderExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.Net.Sockets; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; -using Microsoft.Extensions.Hosting; -using SuperSocket.ProtoBase; -using SuperSocket.Server; -using SuperSocket.Channel; - -namespace SuperSocket.GZip -{ - public static class HostBuilderExtensions - { - - // move to extensions - public static ISuperSocketHostBuilder UseGZip(this ISuperSocketHostBuilder hostBuilder) - { - return hostBuilder.UseChannelCreatorFactory(); - } - - } -} diff --git a/src/SuperSocket.GZip/SuperSocket.GZip.csproj b/src/SuperSocket.GZip/SuperSocket.GZip.csproj deleted file mode 100644 index e3d3c734f..000000000 --- a/src/SuperSocket.GZip/SuperSocket.GZip.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - SuperSocket GZip library which allow you to use gzip compress in secure/normal Tcp channel. - - - - - - - - diff --git a/src/SuperSocket.Primitives/DefaultStringEncoder.cs b/src/SuperSocket.Primitives/DefaultStringEncoder.cs index 234559fb1..bbdbe5d5e 100644 --- a/src/SuperSocket.Primitives/DefaultStringEncoder.cs +++ b/src/SuperSocket.Primitives/DefaultStringEncoder.cs @@ -1,6 +1,5 @@ using System; using System.Buffers; -using System.IO.Pipelines; using System.Text; using SuperSocket.ProtoBase; diff --git a/src/SuperSocket.Primitives/Extensions.cs b/src/SuperSocket.Primitives/Extensions.cs index ddd6ebf8e..376cc770f 100644 --- a/src/SuperSocket.Primitives/Extensions.cs +++ b/src/SuperSocket.Primitives/Extensions.cs @@ -24,28 +24,5 @@ public static ValueTask GetCompletedTask() return _completedTask; } #endif - - public static IPEndPoint GetListenEndPoint(this ListenOptions listenOptions) - { - var ip = listenOptions.Ip; - var port = listenOptions.Port; - - IPAddress ipAddress; - - if ("any".Equals(ip, StringComparison.OrdinalIgnoreCase)) - { - ipAddress = IPAddress.Any; - } - else if ("IpV6Any".Equals(ip, StringComparison.OrdinalIgnoreCase)) - { - ipAddress = IPAddress.IPv6Any; - } - else - { - ipAddress = IPAddress.Parse(ip); - } - - return new IPEndPoint(ipAddress, port); - } } } \ No newline at end of file diff --git a/src/SuperSocket.Primitives/IChannelCreator.cs b/src/SuperSocket.Primitives/IChannelCreator.cs deleted file mode 100644 index e52a03ad3..000000000 --- a/src/SuperSocket.Primitives/IChannelCreator.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Threading.Tasks; -using SuperSocket.Channel; - -namespace SuperSocket -{ - public delegate ValueTask NewClientAcceptHandler(IChannelCreator listener, IChannel channel); - - public interface IChannelCreator - { - ListenOptions Options { get; } - - bool Start(); - - event NewClientAcceptHandler NewClientAccepted; - - Task CreateChannel(object connection); - - Task StopAsync(); - - bool IsRunning { get; } - } -} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/IChannelCreatorFactory.cs b/src/SuperSocket.Primitives/IChannelCreatorFactory.cs deleted file mode 100644 index 84cc84063..000000000 --- a/src/SuperSocket.Primitives/IChannelCreatorFactory.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; - -namespace SuperSocket -{ - public interface IChannelCreatorFactory - { - IChannelCreator CreateChannelCreator(ListenOptions options, ChannelOptions channelOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory); - } -} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/IChannelRegister.cs b/src/SuperSocket.Primitives/IChannelRegister.cs deleted file mode 100644 index 2cb8a62fa..000000000 --- a/src/SuperSocket.Primitives/IChannelRegister.cs +++ /dev/null @@ -1,14 +0,0 @@ - -using System; -using Microsoft.Extensions.Logging; -using SuperSocket.ProtoBase; -using SuperSocket.Channel; -using System.Threading.Tasks; - -namespace SuperSocket -{ - public interface IChannelRegister - { - Task RegisterChannel(object connection); - } -} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/ListenOptions.cs b/src/SuperSocket.Primitives/ListenOptions.cs deleted file mode 100644 index a8e3cf04a..000000000 --- a/src/SuperSocket.Primitives/ListenOptions.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.Security.Authentication; - -namespace SuperSocket -{ - public class ListenOptions - { - public string Ip { get; set; } - - public int Port { get; set; } - - public string Path { get; set; } - - public int BackLog { get; set; } - - public bool NoDelay { get; set; } - - public SslProtocols Security { get; set; } - - public CertificateOptions CertificateOptions { get; set; } - - - public override string ToString() - { - return $"{nameof(Ip)}={Ip}, {nameof(Port)}={Port}, {nameof(Security)}={Security}, {nameof(Path)}={Path}, {nameof(BackLog)}={BackLog}, {nameof(NoDelay)}={NoDelay}"; - } - } -} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/PackageHandlingException.cs b/src/SuperSocket.Primitives/PackageHandlingException.cs index a86d01e96..b869c2b99 100644 --- a/src/SuperSocket.Primitives/PackageHandlingException.cs +++ b/src/SuperSocket.Primitives/PackageHandlingException.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using SuperSocket.Channel; namespace SuperSocket { diff --git a/src/SuperSocket.Primitives/SuperSocket.Primitives.csproj b/src/SuperSocket.Primitives/SuperSocket.Primitives.csproj index 6fee3ef48..b79d54171 100755 --- a/src/SuperSocket.Primitives/SuperSocket.Primitives.csproj +++ b/src/SuperSocket.Primitives/SuperSocket.Primitives.csproj @@ -7,11 +7,9 @@ - - \ No newline at end of file diff --git a/src/SuperSocket.ProtoBase/IPipelineFilterFactory.cs b/src/SuperSocket.ProtoBase/IPipelineFilterFactory.cs index a88a99f5f..8ae5e6d21 100644 --- a/src/SuperSocket.ProtoBase/IPipelineFilterFactory.cs +++ b/src/SuperSocket.ProtoBase/IPipelineFilterFactory.cs @@ -4,4 +4,9 @@ public interface IPipelineFilterFactory { IPipelineFilter Create(object client); } + + public interface IPipelineFilterFactory + { + IPipelineFilter Create(object client); + } } \ No newline at end of file diff --git a/src/SuperSocket.ProtoBase/PipelineFilterFactoryBase.cs b/src/SuperSocket.ProtoBase/PipelineFilterFactoryBase.cs index 0649fe9f9..314f41bed 100644 --- a/src/SuperSocket.ProtoBase/PipelineFilterFactoryBase.cs +++ b/src/SuperSocket.ProtoBase/PipelineFilterFactoryBase.cs @@ -2,7 +2,7 @@ namespace SuperSocket.ProtoBase { - public abstract class PipelineFilterFactoryBase : IPipelineFilterFactory + public abstract class PipelineFilterFactoryBase : IPipelineFilterFactory, IPipelineFilterFactory { protected IPackageDecoder PackageDecoder { get; private set; } @@ -19,5 +19,10 @@ public virtual IPipelineFilter Create(object client) filter.Decoder = PackageDecoder; return filter; } + + IPipelineFilter IPipelineFilterFactory.Create(object client) + { + return this.Create(client) as IPipelineFilter; + } } } \ No newline at end of file diff --git a/src/SuperSocket.Primitives/AsyncEventHandler.cs b/src/SuperSocket.Server.Abstractions/AsyncEventHandler.cs similarity index 90% rename from src/SuperSocket.Primitives/AsyncEventHandler.cs rename to src/SuperSocket.Server.Abstractions/AsyncEventHandler.cs index 7b947e1c6..c6454216f 100644 --- a/src/SuperSocket.Primitives/AsyncEventHandler.cs +++ b/src/SuperSocket.Server.Abstractions/AsyncEventHandler.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public delegate ValueTask AsyncEventHandler(object sender, EventArgs e); diff --git a/src/SuperSocket.Server.Abstractions/Connections/IConnectionFactoryBuilder.cs b/src/SuperSocket.Server.Abstractions/Connections/IConnectionFactoryBuilder.cs new file mode 100644 index 000000000..7e697fb1f --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/Connections/IConnectionFactoryBuilder.cs @@ -0,0 +1,10 @@ + +using SuperSocket.Connection; + +namespace SuperSocket.Server.Abstractions.Connections +{ + public interface IConnectionFactoryBuilder + { + IConnectionFactory Build(ListenOptions listenOptions, ConnectionOptions connectionOptions); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server.Abstractions/Connections/IConnectionListener.cs b/src/SuperSocket.Server.Abstractions/Connections/IConnectionListener.cs new file mode 100644 index 000000000..26da97f93 --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/Connections/IConnectionListener.cs @@ -0,0 +1,26 @@ + +using System; +using Microsoft.Extensions.Logging; +using SuperSocket.ProtoBase; +using SuperSocket.Connection; +using System.Threading.Tasks; + +namespace SuperSocket.Server.Abstractions.Connections +{ + public delegate ValueTask NewConnectionAcceptHandler(ListenOptions listenOptions, IConnection connection); + + public interface IConnectionListener + { + ListenOptions Options { get; } + + bool Start(); + + event NewConnectionAcceptHandler NewConnectionAccept; + + Task StopAsync(); + + bool IsRunning { get; } + + IConnectionFactory ConnectionFactory { get; } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server.Abstractions/Connections/IConnectionListenerFactory.cs b/src/SuperSocket.Server.Abstractions/Connections/IConnectionListenerFactory.cs new file mode 100644 index 000000000..f0a8b50d2 --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/Connections/IConnectionListenerFactory.cs @@ -0,0 +1,10 @@ +using Microsoft.Extensions.Logging; +using SuperSocket.Connection; + +namespace SuperSocket.Server.Abstractions.Connections +{ + public interface IConnectionListenerFactory + { + IConnectionListener CreateConnectionListener(ListenOptions options, ConnectionOptions connectionOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server.Abstractions/Connections/IConnectionRegister.cs b/src/SuperSocket.Server.Abstractions/Connections/IConnectionRegister.cs new file mode 100644 index 000000000..5cd40cf90 --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/Connections/IConnectionRegister.cs @@ -0,0 +1,14 @@ + +using System; +using Microsoft.Extensions.Logging; +using SuperSocket.ProtoBase; +using SuperSocket.Connection; +using System.Threading.Tasks; + +namespace SuperSocket.Server.Abstractions.Connections +{ + public interface IConnectionRegister + { + Task RegisterConnection(object connection); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/DelegatePackageHandler.cs b/src/SuperSocket.Server.Abstractions/DelegatePackageHandler.cs similarity index 85% rename from src/SuperSocket.Primitives/DelegatePackageHandler.cs rename to src/SuperSocket.Server.Abstractions/DelegatePackageHandler.cs index 8302ac844..c1fb1398a 100644 --- a/src/SuperSocket.Primitives/DelegatePackageHandler.cs +++ b/src/SuperSocket.Server.Abstractions/DelegatePackageHandler.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public class DelegatePackageHandler : IPackageHandler { diff --git a/src/SuperSocket.Primitives/HostBuilderExtensions.cs b/src/SuperSocket.Server.Abstractions/Host/HostBuilderExtensions.cs similarity index 75% rename from src/SuperSocket.Primitives/HostBuilderExtensions.cs rename to src/SuperSocket.Server.Abstractions/Host/HostBuilderExtensions.cs index 0beb4459a..d49e85793 100644 --- a/src/SuperSocket.Primitives/HostBuilderExtensions.cs +++ b/src/SuperSocket.Server.Abstractions/Host/HostBuilderExtensions.cs @@ -1,11 +1,12 @@ using System; -using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Middleware; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Host { public static class HostBuilderExtensions { @@ -31,12 +32,12 @@ public static ISuperSocketHostBuilder UseMiddleware(this ISuperSock services.TryAddEnumerable(ServiceDescriptor.Singleton(implementationFactory)); }).AsSuperSocketBuilder(); } - public static ISuperSocketHostBuilder UseChannelCreatorFactory(this ISuperSocketHostBuilder builder) - where TChannelCreatorFactory : class, IChannelCreatorFactory + public static ISuperSocketHostBuilder UseTcpConnectionListenerFactory(this ISuperSocketHostBuilder builder) + where TConnectionListenerFactory : class, IConnectionListenerFactory { return builder.ConfigureServices((ctx, services) => { - services.AddSingleton(); + services.AddSingleton(); }).AsSuperSocketBuilder(); } } diff --git a/src/SuperSocket.Primitives/IMinimalApiHostBuilder.cs b/src/SuperSocket.Server.Abstractions/Host/IMinimalApiHostBuilder.cs similarity index 70% rename from src/SuperSocket.Primitives/IMinimalApiHostBuilder.cs rename to src/SuperSocket.Server.Abstractions/Host/IMinimalApiHostBuilder.cs index 3702a3a6b..f349f0c6c 100644 --- a/src/SuperSocket.Primitives/IMinimalApiHostBuilder.cs +++ b/src/SuperSocket.Server.Abstractions/Host/IMinimalApiHostBuilder.cs @@ -1,6 +1,6 @@ using System; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Host { public interface IMinimalApiHostBuilder { diff --git a/src/SuperSocket.Primitives/ISuperSocketHostBuilder.cs b/src/SuperSocket.Server.Abstractions/Host/ISuperSocketHostBuilder.cs similarity index 94% rename from src/SuperSocket.Primitives/ISuperSocketHostBuilder.cs rename to src/SuperSocket.Server.Abstractions/Host/ISuperSocketHostBuilder.cs index b29e0a8f4..a0d558dfd 100644 --- a/src/SuperSocket.Primitives/ISuperSocketHostBuilder.cs +++ b/src/SuperSocket.Server.Abstractions/Host/ISuperSocketHostBuilder.cs @@ -3,8 +3,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Middleware; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Host { public interface ISuperSocketHostBuilder : IHostBuilder, IMinimalApiHostBuilder { diff --git a/src/SuperSocket.Primitives/IPackageHandler.cs b/src/SuperSocket.Server.Abstractions/IPackageHandler.cs similarity index 68% rename from src/SuperSocket.Primitives/IPackageHandler.cs rename to src/SuperSocket.Server.Abstractions/IPackageHandler.cs index 711dfe250..50e868a3f 100644 --- a/src/SuperSocket.Primitives/IPackageHandler.cs +++ b/src/SuperSocket.Server.Abstractions/IPackageHandler.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public interface IPackageHandler { diff --git a/src/SuperSocket.Primitives/IPackageHandlingScheduler.cs b/src/SuperSocket.Server.Abstractions/IPackageHandlingScheduler.cs similarity index 77% rename from src/SuperSocket.Primitives/IPackageHandlingScheduler.cs rename to src/SuperSocket.Server.Abstractions/IPackageHandlingScheduler.cs index e7b3b2796..4d223c3a4 100644 --- a/src/SuperSocket.Primitives/IPackageHandlingScheduler.cs +++ b/src/SuperSocket.Server.Abstractions/IPackageHandlingScheduler.cs @@ -2,9 +2,10 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public interface IPackageHandlingScheduler { diff --git a/src/SuperSocket.Primitives/IServer.cs b/src/SuperSocket.Server.Abstractions/IServer.cs similarity index 82% rename from src/SuperSocket.Primitives/IServer.cs rename to src/SuperSocket.Server.Abstractions/IServer.cs index af08dc741..5cb8c98e2 100644 --- a/src/SuperSocket.Primitives/IServer.cs +++ b/src/SuperSocket.Server.Abstractions/IServer.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public interface IServer : IServerInfo, IDisposable, IAsyncDisposable { diff --git a/src/SuperSocket.Primitives/IServerInfo.cs b/src/SuperSocket.Server.Abstractions/IServerInfo.cs similarity index 87% rename from src/SuperSocket.Primitives/IServerInfo.cs rename to src/SuperSocket.Server.Abstractions/IServerInfo.cs index bac4bca04..123173b07 100644 --- a/src/SuperSocket.Primitives/IServerInfo.cs +++ b/src/SuperSocket.Server.Abstractions/IServerInfo.cs @@ -1,6 +1,6 @@ using System; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public interface IServerInfo { diff --git a/src/SuperSocket.Server.Abstractions/ISuperSocketHostedService.cs b/src/SuperSocket.Server.Abstractions/ISuperSocketHostedService.cs new file mode 100644 index 000000000..3a25451b7 --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/ISuperSocketHostedService.cs @@ -0,0 +1,14 @@ +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using SuperSocket; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; + +namespace SuperSocket.Server.Abstractions +{ + public interface ISuperSocketHostedService : IHostedService, IServer, IConnectionRegister, ILoggerAccessor, ISessionEventHost + { + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server.Abstractions/ListenOptions.cs b/src/SuperSocket.Server.Abstractions/ListenOptions.cs new file mode 100644 index 000000000..d87b9aa8b --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/ListenOptions.cs @@ -0,0 +1,53 @@ +using System; +using System.Net; +using System.Security.Authentication; + +namespace SuperSocket.Server.Abstractions +{ + public class ListenOptions + { + public string Ip { get; set; } + + public int Port { get; set; } + + public string Path { get; set; } + + public int BackLog { get; set; } + + public bool NoDelay { get; set; } + + public SslProtocols Security { get; set; } + + public CertificateOptions CertificateOptions { get; set; } + + public TimeSpan ConnectionAcceptTimeOut { get; set; } = TimeSpan.FromSeconds(5); + + public IPEndPoint ToEndPoint() + { + var ip = this.Ip; + var port = this.Port; + + IPAddress ipAddress; + + if ("any".Equals(ip, StringComparison.OrdinalIgnoreCase)) + { + ipAddress = IPAddress.Any; + } + else if ("IpV6Any".Equals(ip, StringComparison.OrdinalIgnoreCase)) + { + ipAddress = IPAddress.IPv6Any; + } + else + { + ipAddress = IPAddress.Parse(ip); + } + + return new IPEndPoint(ipAddress, port); + } + + public override string ToString() + { + return $"{nameof(Ip)}={Ip}, {nameof(Port)}={Port}, {nameof(Security)}={Security}, {nameof(Path)}={Path}, {nameof(BackLog)}={BackLog}, {nameof(NoDelay)}={NoDelay}"; + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/IMiddleware.cs b/src/SuperSocket.Server.Abstractions/Middleware/IMiddleware.cs similarity index 75% rename from src/SuperSocket.Primitives/IMiddleware.cs rename to src/SuperSocket.Server.Abstractions/Middleware/IMiddleware.cs index b50546cc3..4a4e2a7e9 100644 --- a/src/SuperSocket.Primitives/IMiddleware.cs +++ b/src/SuperSocket.Server.Abstractions/Middleware/IMiddleware.cs @@ -1,7 +1,8 @@ using System.Threading.Tasks; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Middleware { public interface IMiddleware { diff --git a/src/SuperSocket.Primitives/MiddlewareBase.cs b/src/SuperSocket.Server.Abstractions/Middleware/MiddlewareBase.cs similarity index 85% rename from src/SuperSocket.Primitives/MiddlewareBase.cs rename to src/SuperSocket.Server.Abstractions/Middleware/MiddlewareBase.cs index 363b3e5ac..5426242a1 100644 --- a/src/SuperSocket.Primitives/MiddlewareBase.cs +++ b/src/SuperSocket.Server.Abstractions/Middleware/MiddlewareBase.cs @@ -1,7 +1,8 @@ using System.Threading.Tasks; +using SuperSocket.Server.Abstractions.Session; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Middleware { public abstract class MiddlewareBase : IMiddleware { diff --git a/src/SuperSocket.Primitives/ServerOptions.cs b/src/SuperSocket.Server.Abstractions/ServerOptions.cs similarity index 74% rename from src/SuperSocket.Primitives/ServerOptions.cs rename to src/SuperSocket.Server.Abstractions/ServerOptions.cs index de16805bc..564402507 100644 --- a/src/SuperSocket.Primitives/ServerOptions.cs +++ b/src/SuperSocket.Server.Abstractions/ServerOptions.cs @@ -1,10 +1,10 @@ using System.Collections.Generic; using System.Text; -using SuperSocket.Channel; +using SuperSocket.Connection; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { - public class ServerOptions : ChannelOptions + public class ServerOptions : ConnectionOptions { public string Name { get; set; } diff --git a/src/SuperSocket.Primitives/ServerState.cs b/src/SuperSocket.Server.Abstractions/ServerState.cs similarity index 89% rename from src/SuperSocket.Primitives/ServerState.cs rename to src/SuperSocket.Server.Abstractions/ServerState.cs index 01589302a..d1ed2958c 100644 --- a/src/SuperSocket.Primitives/ServerState.cs +++ b/src/SuperSocket.Server.Abstractions/ServerState.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public enum ServerState { diff --git a/src/SuperSocket.Primitives/AsyncToSyncSessionContainerWrapper.cs b/src/SuperSocket.Server.Abstractions/Session/AsyncToSyncSessionContainerWrapper.cs similarity index 93% rename from src/SuperSocket.Primitives/AsyncToSyncSessionContainerWrapper.cs rename to src/SuperSocket.Server.Abstractions/Session/AsyncToSyncSessionContainerWrapper.cs index 36a61821b..81999c438 100644 --- a/src/SuperSocket.Primitives/AsyncToSyncSessionContainerWrapper.cs +++ b/src/SuperSocket.Server.Abstractions/Session/AsyncToSyncSessionContainerWrapper.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public class AsyncToSyncSessionContainerWrapper : ISessionContainer { diff --git a/src/SuperSocket.Primitives/IAppSession.cs b/src/SuperSocket.Server.Abstractions/Session/IAppSession.cs similarity index 82% rename from src/SuperSocket.Primitives/IAppSession.cs rename to src/SuperSocket.Server.Abstractions/Session/IAppSession.cs index 6f0e1b876..dffd0bd2e 100644 --- a/src/SuperSocket.Primitives/IAppSession.cs +++ b/src/SuperSocket.Server.Abstractions/Session/IAppSession.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public interface IAppSession { @@ -15,7 +15,7 @@ public interface IAppSession DateTimeOffset LastActiveTime { get; } - IChannel Channel { get; } + IConnection Connection { get; } EndPoint RemoteEndPoint { get; } @@ -35,7 +35,7 @@ public interface IAppSession object DataContext { get; set; } - void Initialize(IServerInfo server, IChannel channel); + void Initialize(IServerInfo server, IConnection connection); object this[object name] { get; set; } diff --git a/src/SuperSocket.Primitives/IHandshakeRequiredSession.cs b/src/SuperSocket.Server.Abstractions/Session/IHandshakeRequiredSession.cs similarity index 71% rename from src/SuperSocket.Primitives/IHandshakeRequiredSession.cs rename to src/SuperSocket.Server.Abstractions/Session/IHandshakeRequiredSession.cs index f1239e0d7..44b8640b2 100644 --- a/src/SuperSocket.Primitives/IHandshakeRequiredSession.cs +++ b/src/SuperSocket.Server.Abstractions/Session/IHandshakeRequiredSession.cs @@ -2,10 +2,8 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public interface IHandshakeRequiredSession { diff --git a/src/SuperSocket.Primitives/ISessionContainer.cs b/src/SuperSocket.Server.Abstractions/Session/ISessionContainer.cs similarity index 94% rename from src/SuperSocket.Primitives/ISessionContainer.cs rename to src/SuperSocket.Server.Abstractions/Session/ISessionContainer.cs index 3ea61797d..ab04effb9 100644 --- a/src/SuperSocket.Primitives/ISessionContainer.cs +++ b/src/SuperSocket.Server.Abstractions/Session/ISessionContainer.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using SuperSocket.Channel; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public interface ISessionContainer { diff --git a/src/SuperSocket.Server.Abstractions/Session/ISessionEventHost.cs b/src/SuperSocket.Server.Abstractions/Session/ISessionEventHost.cs new file mode 100644 index 000000000..9cefee51d --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/Session/ISessionEventHost.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using SuperSocket.Connection; + +namespace SuperSocket.Server.Abstractions.Session +{ + public interface ISessionEventHost + { + ValueTask HandleSessionConnectedEvent(IAppSession session); + + ValueTask HandleSessionClosedEvent(IAppSession session, CloseReason reason); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Primitives/ISessionFactory.cs b/src/SuperSocket.Server.Abstractions/Session/ISessionFactory.cs similarity index 72% rename from src/SuperSocket.Primitives/ISessionFactory.cs rename to src/SuperSocket.Server.Abstractions/Session/ISessionFactory.cs index cfb38caaa..cb50a7e89 100644 --- a/src/SuperSocket.Primitives/ISessionFactory.cs +++ b/src/SuperSocket.Server.Abstractions/Session/ISessionFactory.cs @@ -1,7 +1,6 @@ using System; -using SuperSocket.Channel; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public interface ISessionFactory { diff --git a/src/SuperSocket.SessionContainer/InProcSessionContainerMiddleware.cs b/src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddleware.cs similarity index 96% rename from src/SuperSocket.SessionContainer/InProcSessionContainerMiddleware.cs rename to src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddleware.cs index 32a8ed4d1..446a6098e 100644 --- a/src/SuperSocket.SessionContainer/InProcSessionContainerMiddleware.cs +++ b/src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddleware.cs @@ -4,9 +4,9 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Middleware; -namespace SuperSocket.SessionContainer +namespace SuperSocket.Server.Abstractions.Session { public class InProcSessionContainerMiddleware : MiddlewareBase, ISessionContainer { diff --git a/src/SuperSocket.SessionContainer/InProcSessionContainerMiddlewareExtensions.cs b/src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddlewareExtensions.cs similarity index 91% rename from src/SuperSocket.SessionContainer/InProcSessionContainerMiddlewareExtensions.cs rename to src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddlewareExtensions.cs index 00edfddfa..fa5174d92 100644 --- a/src/SuperSocket.SessionContainer/InProcSessionContainerMiddlewareExtensions.cs +++ b/src/SuperSocket.Server.Abstractions/Session/InProcSessionContainerMiddlewareExtensions.cs @@ -1,10 +1,10 @@ using System; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; -using SuperSocket.SessionContainer; using Microsoft.Extensions.DependencyInjection.Extensions; +using SuperSocket.Server.Abstractions.Host; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public static class InProcSessionContainerMiddlewareExtensions { diff --git a/src/SuperSocket.Primitives/SessionContainerExtensions.cs b/src/SuperSocket.Server.Abstractions/Session/SessionContainerExtensions.cs similarity index 96% rename from src/SuperSocket.Primitives/SessionContainerExtensions.cs rename to src/SuperSocket.Server.Abstractions/Session/SessionContainerExtensions.cs index 88c218628..aabb87423 100644 --- a/src/SuperSocket.Primitives/SessionContainerExtensions.cs +++ b/src/SuperSocket.Server.Abstractions/Session/SessionContainerExtensions.cs @@ -3,8 +3,9 @@ using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; +using SuperSocket.Server.Abstractions.Middleware; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public static class SessionContainerExtensions { diff --git a/src/SuperSocket.Primitives/SessionState.cs b/src/SuperSocket.Server.Abstractions/Session/SessionState.cs similarity index 81% rename from src/SuperSocket.Primitives/SessionState.cs rename to src/SuperSocket.Server.Abstractions/Session/SessionState.cs index dc52915cb..6587d8c55 100644 --- a/src/SuperSocket.Primitives/SessionState.cs +++ b/src/SuperSocket.Server.Abstractions/Session/SessionState.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using SuperSocket.Channel; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions { public enum SessionState { diff --git a/src/SuperSocket.Server.Abstractions/SuperSocket.Server.Abstractions.csproj b/src/SuperSocket.Server.Abstractions/SuperSocket.Server.Abstractions.csproj new file mode 100644 index 000000000..9baf90f80 --- /dev/null +++ b/src/SuperSocket.Server.Abstractions/SuperSocket.Server.Abstractions.csproj @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/src/SuperSocket.Primitives/SyncToAsyncSessionContainerWrapper.cs b/src/SuperSocket.Server.Abstractions/SyncToAsyncSessionContainerWrapper.cs similarity index 94% rename from src/SuperSocket.Primitives/SyncToAsyncSessionContainerWrapper.cs rename to src/SuperSocket.Server.Abstractions/SyncToAsyncSessionContainerWrapper.cs index ce85c3629..d5d912573 100644 --- a/src/SuperSocket.Primitives/SyncToAsyncSessionContainerWrapper.cs +++ b/src/SuperSocket.Server.Abstractions/SyncToAsyncSessionContainerWrapper.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; -namespace SuperSocket +namespace SuperSocket.Server.Abstractions.Session { public class SyncToAsyncSessionContainerWrapper : IAsyncSessionContainer { diff --git a/src/SuperSocket.Server/AppSession.cs b/src/SuperSocket.Server/AppSession.cs index a9ae6c762..44d265f87 100644 --- a/src/SuperSocket.Server/AppSession.cs +++ b/src/SuperSocket.Server/AppSession.cs @@ -3,18 +3,20 @@ using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { public class AppSession : IAppSession, ILogger, ILoggerAccessor { - private IChannel _channel; + private IConnection _connection; - protected internal IChannel Channel + protected internal IConnection Connection { - get { return _channel; } + get { return _connection; } } public AppSession() @@ -22,16 +24,16 @@ public AppSession() } - void IAppSession.Initialize(IServerInfo server, IChannel channel) + void IAppSession.Initialize(IServerInfo server, IConnection connection) { - if (channel is IChannelWithSessionIdentifier channelWithSessionIdentifier) - SessionID = channelWithSessionIdentifier.SessionIdentifier; + if (connection is IConnectionWithSessionIdentifier connectionWithSessionIdentifier) + SessionID = connectionWithSessionIdentifier.SessionIdentifier; else SessionID = Guid.NewGuid().ToString(); Server = server; StartTime = DateTimeOffset.Now; - _channel = channel; + _connection = connection; State = SessionState.Initialized; } @@ -43,26 +45,26 @@ void IAppSession.Initialize(IServerInfo server, IChannel channel) public IServerInfo Server { get; private set; } - IChannel IAppSession.Channel + IConnection IAppSession.Connection { - get { return _channel; } + get { return _connection; } } public object DataContext { get; set; } public EndPoint RemoteEndPoint { - get { return _channel?.RemoteEndPoint; } + get { return _connection?.RemoteEndPoint; } } public EndPoint LocalEndPoint { - get { return _channel?.LocalEndPoint; } + get { return _connection?.LocalEndPoint; } } public DateTimeOffset LastActiveTime { - get { return _channel?.LastActiveTime ?? DateTimeOffset.MinValue; } + get { return _connection?.LastActiveTime ?? DateTimeOffset.MinValue; } } public event AsyncEventHandler Connected; @@ -143,12 +145,12 @@ internal async ValueTask FireSessionConnectedAsync() ValueTask IAppSession.SendAsync(ReadOnlyMemory data) { - return _channel.SendAsync(data); + return _connection.SendAsync(data); } ValueTask IAppSession.SendAsync(IPackageEncoder packageEncoder, TPackage package) { - return _channel.SendAsync(packageEncoder, package); + return _connection.SendAsync(packageEncoder, package); } void IAppSession.Reset() @@ -157,7 +159,7 @@ void IAppSession.Reset() ClearEvent(ref Closed); _items?.Clear(); State = SessionState.None; - _channel = null; + _connection = null; DataContext = null; StartTime = default(DateTimeOffset); Server = null; @@ -189,14 +191,14 @@ public virtual async ValueTask CloseAsync() public virtual async ValueTask CloseAsync(CloseReason reason) { - var channel = Channel; + var connection = Connection; - if (channel == null) + if (connection == null) return; try { - await channel.CloseAsync(reason); + await connection.CloseAsync(reason); } catch { diff --git a/src/SuperSocket.Server/ClearIdleSessionMiddleware.cs b/src/SuperSocket.Server/ClearIdleSessionMiddleware.cs index c53165557..f21568c84 100644 --- a/src/SuperSocket.Server/ClearIdleSessionMiddleware.cs +++ b/src/SuperSocket.Server/ClearIdleSessionMiddleware.cs @@ -4,7 +4,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; namespace SuperSocket.Server { @@ -48,7 +51,7 @@ private void OnTimerCallback(object state) { try { - s.Channel.CloseAsync(CloseReason.TimeOut); + s.Connection.CloseAsync(CloseReason.TimeOut); _logger.LogWarning($"Close the idle session {s.SessionID}, it's LastActiveTime is {s.LastActiveTime}."); } catch (Exception exc) diff --git a/src/SuperSocket.Server/ConcurrentPackageHandlingScheduler.cs b/src/SuperSocket.Server/ConcurrentPackageHandlingScheduler.cs index 0b693dfbb..52d2f5fef 100644 --- a/src/SuperSocket.Server/ConcurrentPackageHandlingScheduler.cs +++ b/src/SuperSocket.Server/ConcurrentPackageHandlingScheduler.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/Connection/ConnectionFactoryBuilder.cs b/src/SuperSocket.Server/Connection/ConnectionFactoryBuilder.cs new file mode 100644 index 000000000..1d327876e --- /dev/null +++ b/src/SuperSocket.Server/Connection/ConnectionFactoryBuilder.cs @@ -0,0 +1,31 @@ +using System; +using System.Net; +using System.Net.Sockets; +using SuperSocket.ProtoBase; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; + +namespace SuperSocket.Server.Connection +{ + public class ConnectionFactoryBuilder : IConnectionFactoryBuilder + { + public Action SocketOptionsSetter { get; } + + public IPipelineFilterFactory PipelineFilterFactory { get; } + + public IConnectionStreamInitializersFactory ConnectionStreamInitializersFactory { get; } + + public ConnectionFactoryBuilder(SocketOptionsSetter socketOptionsSetter, IPipelineFilterFactory pipelineFilterFactory, IConnectionStreamInitializersFactory connectionStreamInitializersFactory) + { + SocketOptionsSetter = socketOptionsSetter.Setter; + PipelineFilterFactory = pipelineFilterFactory; + ConnectionStreamInitializersFactory = connectionStreamInitializersFactory; + } + + public virtual IConnectionFactory Build(ListenOptions listenOptions, ConnectionOptions connectionOptions) + { + return new TcpConnectionFactory(listenOptions, connectionOptions, SocketOptionsSetter, PipelineFilterFactory as IPipelineFilterFactory, ConnectionStreamInitializersFactory); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/DefaultConnectionStreamInitializersFactory.cs b/src/SuperSocket.Server/Connection/DefaultConnectionStreamInitializersFactory.cs new file mode 100644 index 000000000..a195eebdf --- /dev/null +++ b/src/SuperSocket.Server/Connection/DefaultConnectionStreamInitializersFactory.cs @@ -0,0 +1,56 @@ +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public class DefaultConnectionStreamInitializersFactory : IConnectionStreamInitializersFactory + { + public CompressionLevel CompressionLevel { get; } + + private IEnumerable _empty = new IConnectionStreamInitializer[0]; + + public DefaultConnectionStreamInitializersFactory() + : this(CompressionLevel.NoCompression) + { + + } + + public DefaultConnectionStreamInitializersFactory(CompressionLevel compressionLevel) + { + CompressionLevel = compressionLevel; + } + + public virtual IEnumerable Create(ListenOptions listenOptions) + { + var connectionStreamInitializers = new List(); + + if (listenOptions.Security != SslProtocols.None) + { + connectionStreamInitializers.Add(new NetworkStreamInitializer()); + connectionStreamInitializers.Add(new SslStreamInitializer()); + } + + if (CompressionLevel != CompressionLevel.NoCompression) + { + if (!connectionStreamInitializers.Any()) + { + connectionStreamInitializers.Add(new NetworkStreamInitializer()); + } + + connectionStreamInitializers.Add(new GZipStreamInitializer()); + } + + connectionStreamInitializers.ForEach(initializer => initializer.Setup(listenOptions)); + + return connectionStreamInitializers; + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/GZipStreamInitializer.cs b/src/SuperSocket.Server/Connection/GZipStreamInitializer.cs new file mode 100644 index 000000000..6576cff81 --- /dev/null +++ b/src/SuperSocket.Server/Connection/GZipStreamInitializer.cs @@ -0,0 +1,30 @@ +using System.IO; +using System.IO.Compression; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public class GZipStreamInitializer : IConnectionStreamInitializer + { + public CompressionLevel CompressionLevel { get; private set; } + + public Task InitializeAsync(Socket socket, Stream stream, CancellationToken cancellationToken) + { + var connectionStream = new ReadWriteDelegateStream( + stream, + new GZipStream(stream, CompressionMode.Decompress), + new GZipStream(stream, CompressionLevel)); + + return Task.FromResult(connectionStream); + } + + public void Setup(ListenOptions listenOptions) + { + CompressionLevel = CompressionLevel.Optimal; + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/IConnectionStreamInitializer.cs b/src/SuperSocket.Server/Connection/IConnectionStreamInitializer.cs new file mode 100644 index 000000000..9a8c0e3f6 --- /dev/null +++ b/src/SuperSocket.Server/Connection/IConnectionStreamInitializer.cs @@ -0,0 +1,15 @@ +using System.IO; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public interface IConnectionStreamInitializer + { + void Setup(ListenOptions listenOptions); + + Task InitializeAsync(Socket socket, Stream stream, CancellationToken cancellationToken); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/IConnectionStreamInitializersFactory.cs b/src/SuperSocket.Server/Connection/IConnectionStreamInitializersFactory.cs new file mode 100644 index 000000000..925cfa59a --- /dev/null +++ b/src/SuperSocket.Server/Connection/IConnectionStreamInitializersFactory.cs @@ -0,0 +1,15 @@ +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public interface IConnectionStreamInitializersFactory + { + IEnumerable Create(ListenOptions listenOptions); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/NetworkStreamInitializer.cs b/src/SuperSocket.Server/Connection/NetworkStreamInitializer.cs new file mode 100644 index 000000000..e407d1110 --- /dev/null +++ b/src/SuperSocket.Server/Connection/NetworkStreamInitializer.cs @@ -0,0 +1,20 @@ +using System.IO; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public class NetworkStreamInitializer : IConnectionStreamInitializer + { + public void Setup(ListenOptions listenOptions) + { + } + + public Task InitializeAsync(Socket socket, Stream stream, CancellationToken cancellationToken) + { + return Task.FromResult(new NetworkStream(socket, true)); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/SslStreamInitializer.cs b/src/SuperSocket.Server/Connection/SslStreamInitializer.cs new file mode 100644 index 000000000..37068fd49 --- /dev/null +++ b/src/SuperSocket.Server/Connection/SslStreamInitializer.cs @@ -0,0 +1,42 @@ +using System.IO; +using System.Net.Security; +using System.Net.Sockets; +using System.Runtime.Serialization.Formatters; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Server.Abstractions; + +namespace SuperSocket.Server.Connection +{ + public class SslStreamInitializer : IConnectionStreamInitializer + { + private SslServerAuthenticationOptions _authOptions; + + public void Setup(ListenOptions listenOptions) + { + var authOptions = new SslServerAuthenticationOptions(); + + authOptions.EnabledSslProtocols = listenOptions.Security; + + if (listenOptions.CertificateOptions.Certificate == null) + { + listenOptions.CertificateOptions.EnsureCertificate(); + } + + authOptions.ServerCertificate = listenOptions.CertificateOptions.Certificate; + authOptions.ClientCertificateRequired = listenOptions.CertificateOptions.ClientCertificateRequired; + + if (listenOptions.CertificateOptions.RemoteCertificateValidationCallback != null) + authOptions.RemoteCertificateValidationCallback = listenOptions.CertificateOptions.RemoteCertificateValidationCallback; + + _authOptions = authOptions; + } + + public async Task InitializeAsync(Socket socket, Stream stream, CancellationToken cancellationToken) + { + var sslStream = new SslStream(stream, false); + await sslStream.AuthenticateAsServerAsync(_authOptions, cancellationToken); + return sslStream; + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/Connection/TcpConnectionFactory.cs b/src/SuperSocket.Server/Connection/TcpConnectionFactory.cs new file mode 100644 index 000000000..2e359c095 --- /dev/null +++ b/src/SuperSocket.Server/Connection/TcpConnectionFactory.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.IO; +using System.Linq; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using SuperSocket.Connection; +using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; + +namespace SuperSocket.Server.Connection +{ + public class TcpConnectionFactory : IConnectionFactory + { + protected ListenOptions ListenOptions { get; } + + protected ConnectionOptions ConnectionOptions { get; } + + protected Action SocketOptionsSetter { get; } + + protected IPipelineFilterFactory PipelineFilterFactory; + + protected ILogger Logger { get; } + + private IEnumerable _connectionStreamInitializers; + + public TcpConnectionFactory( + ListenOptions listenOptions, + ConnectionOptions connectionOptions, + Action socketOptionsSetter, + IPipelineFilterFactory pipelineFilterFactory, + IConnectionStreamInitializersFactory connectionStreamInitializersFactory) + { + ListenOptions = listenOptions; + ConnectionOptions = connectionOptions; + SocketOptionsSetter = socketOptionsSetter; + PipelineFilterFactory = pipelineFilterFactory; + Logger = connectionOptions.Logger; + + _connectionStreamInitializers = connectionStreamInitializersFactory.Create(listenOptions); + } + + public virtual async Task CreateConnection(object connection, CancellationToken cancellationToken) + { + var socket = connection as Socket; + + ApplySocketOptions(socket); + + if (_connectionStreamInitializers is IEnumerable connectionStreamInitializers + && connectionStreamInitializers.Any()) + { + var stream = default(Stream); + + foreach (var initializer in connectionStreamInitializers) + { + stream = await initializer.InitializeAsync(socket, stream, cancellationToken); + } + + return new StreamPipeConnection(stream, socket.RemoteEndPoint, socket.LocalEndPoint, PipelineFilterFactory.Create(socket), ConnectionOptions); + } + + return new TcpPipeConnection(socket, PipelineFilterFactory.Create(socket), ConnectionOptions); + } + + protected virtual void ApplySocketOptions(Socket socket) + { + try + { + if (ListenOptions.NoDelay) + socket.NoDelay = true; + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to set NoDelay for the socket."); + } + + try + { + if (ConnectionOptions.ReceiveBufferSize > 0) + socket.ReceiveBufferSize = ConnectionOptions.ReceiveBufferSize; + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to set ReceiveBufferSize for the socket."); + } + + try + { + if (ConnectionOptions.SendBufferSize > 0) + socket.SendBufferSize = ConnectionOptions.SendBufferSize; + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to set SendBufferSize for the socket."); + } + + try + { + if (ConnectionOptions.ReceiveTimeout > 0) + socket.ReceiveTimeout = ConnectionOptions.ReceiveTimeout; + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to set ReceiveTimeout for the socket."); + } + + try + { + if (ConnectionOptions.SendTimeout > 0) + socket.SendTimeout = ConnectionOptions.SendTimeout; + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to set SendTimeout for the socket."); + } + + try + { + SocketOptionsSetter?.Invoke(socket); + } + catch (Exception e) + { + Logger.LogWarning(e, "Failed to run socketOptionSetter for the socket."); + } + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/TcpChannelCreator.cs b/src/SuperSocket.Server/Connection/TcpConnectionListener.cs similarity index 77% rename from src/SuperSocket.Server/TcpChannelCreator.cs rename to src/SuperSocket.Server/Connection/TcpConnectionListener.cs index ad05e36c2..d5aa8d831 100644 --- a/src/SuperSocket.Server/TcpChannelCreator.cs +++ b/src/SuperSocket.Server/Connection/TcpConnectionListener.cs @@ -2,27 +2,28 @@ using System.Net.Sockets; using System.Threading.Tasks; using System.Threading; -using System.Net; -using SuperSocket.Channel; +using SuperSocket.Connection; using Microsoft.Extensions.Logging; using System.Security.Authentication; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; -namespace SuperSocket.Server +namespace SuperSocket.Server.Connection { - public class TcpChannelCreator : IChannelCreator + public class TcpConnectionListener : IConnectionListener { private Socket _listenSocket; private CancellationTokenSource _cancellationTokenSource; private TaskCompletionSource _stopTaskCompletionSource; - private readonly Func> _channelFactory; + public IConnectionFactory ConnectionFactory { get; } public ListenOptions Options { get; } private ILogger _logger; - public TcpChannelCreator(ListenOptions options, Func> channelFactory, ILogger logger) + public TcpConnectionListener(ListenOptions options, IConnectionFactory connectionFactory, ILogger logger) { Options = options; - _channelFactory = channelFactory; + ConnectionFactory = connectionFactory; _logger = logger; } @@ -34,12 +35,7 @@ public bool Start() try { - if (options.Security != SslProtocols.None && options.CertificateOptions != null) - { - options.CertificateOptions.EnsureCertificate(); - } - - var listenEndpoint = options.GetListenEndPoint(); + var listenEndpoint = options.ToEndPoint(); var listenSocket = _listenSocket = new Socket(listenEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); @@ -98,20 +94,21 @@ private async Task KeepAccept(Socket listenSocket) _stopTaskCompletionSource.TrySetResult(true); } - public event NewClientAcceptHandler NewClientAccepted; + public event NewConnectionAcceptHandler NewConnectionAccept; private async void OnNewClientAccept(Socket socket) { - var handler = NewClientAccepted; + var handler = NewConnectionAccept; if (handler == null) return; - IChannel channel = null; + IConnection connection = null; try { - channel = await _channelFactory(socket); + using var cts = new CancellationTokenSource(Options.ConnectionAcceptTimeOut); + connection = await ConnectionFactory.CreateConnection(socket, cts.Token); } catch (Exception e) { @@ -119,12 +116,7 @@ private async void OnNewClientAccept(Socket socket) return; } - await handler.Invoke(this, channel); - } - - public async Task CreateChannel(object connection) - { - return await _channelFactory((Socket)connection); + await handler.Invoke(this.Options, connection); } public Task StopAsync() diff --git a/src/SuperSocket.Server/Connection/TcpConnectionListenerFactory.cs b/src/SuperSocket.Server/Connection/TcpConnectionListenerFactory.cs new file mode 100644 index 000000000..a25af999d --- /dev/null +++ b/src/SuperSocket.Server/Connection/TcpConnectionListenerFactory.cs @@ -0,0 +1,45 @@ +using System; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; +using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Connection; +using System.Net; +using Microsoft.Extensions.Options; + +namespace SuperSocket.Server.Connection +{ + public class TcpConnectionListenerFactory : IConnectionListenerFactory + { + protected IConnectionFactoryBuilder ConnectionFactoryBuilder { get; } + + public TcpConnectionListenerFactory(IConnectionFactoryBuilder connectionFactoryBuilder) + { + ConnectionFactoryBuilder = connectionFactoryBuilder; + } + + public virtual IConnectionListener CreateConnectionListener(ListenOptions options, ConnectionOptions connectionOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory) + { + var filterFactory = pipelineFilterFactory as IPipelineFilterFactory; + connectionOptions.Logger = loggerFactory.CreateLogger(nameof(IConnection)); + + var connectionListenerLogger = loggerFactory.CreateLogger(nameof(TcpConnectionListener)); + + return new TcpConnectionListener( + options, + CreateTcpConnectionFactory(options, connectionOptions), + connectionListenerLogger); + } + + protected virtual IConnectionFactory CreateTcpConnectionFactory(ListenOptions options, ConnectionOptions connectionOptions) + { + return ConnectionFactoryBuilder.Build(options, connectionOptions); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/DefaultSessionFactory.cs b/src/SuperSocket.Server/DefaultSessionFactory.cs index bd9942a0a..46b000ac6 100644 --- a/src/SuperSocket.Server/DefaultSessionFactory.cs +++ b/src/SuperSocket.Server/DefaultSessionFactory.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/DefaultStringEncoderForDI.cs b/src/SuperSocket.Server/DefaultStringEncoderForDI.cs index 39a8b25c9..78ddd4c41 100644 --- a/src/SuperSocket.Server/DefaultStringEncoderForDI.cs +++ b/src/SuperSocket.Server/DefaultStringEncoderForDI.cs @@ -3,6 +3,7 @@ using System.Text; using Microsoft.Extensions.Options; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; namespace SuperSocket { diff --git a/src/SuperSocket.Server/GenericSessionFactory.cs b/src/SuperSocket.Server/GenericSessionFactory.cs index f02792186..1bb0904e5 100644 --- a/src/SuperSocket.Server/GenericSessionFactory.cs +++ b/src/SuperSocket.Server/GenericSessionFactory.cs @@ -2,7 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using System.Linq; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/HostBuilderAdapter.cs b/src/SuperSocket.Server/Host/HostBuilderAdapter.cs similarity index 96% rename from src/SuperSocket.Server/HostBuilderAdapter.cs rename to src/SuperSocket.Server/Host/HostBuilderAdapter.cs index 02061884a..56aaadbc9 100644 --- a/src/SuperSocket.Server/HostBuilderAdapter.cs +++ b/src/SuperSocket.Server/Host/HostBuilderAdapter.cs @@ -6,10 +6,9 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; +using GenericHost = Microsoft.Extensions.Hosting.Host; -namespace SuperSocket.Server +namespace SuperSocket.Server.Host { public abstract class HostBuilderAdapter : IHostBuilder where THostBuilder : HostBuilderAdapter @@ -23,7 +22,7 @@ public HostBuilderAdapter() } public HostBuilderAdapter(string[] args) - : this(Host.CreateDefaultBuilder(args)) + : this(GenericHost.CreateDefaultBuilder(args)) { } diff --git a/src/SuperSocket.Server/HostBuilderExtensions.cs b/src/SuperSocket.Server/Host/HostBuilderExtensions.cs similarity index 89% rename from src/SuperSocket.Server/HostBuilderExtensions.cs rename to src/SuperSocket.Server/Host/HostBuilderExtensions.cs index 05a010d78..14ae3ec0c 100644 --- a/src/SuperSocket.Server/HostBuilderExtensions.cs +++ b/src/SuperSocket.Server/Host/HostBuilderExtensions.cs @@ -4,13 +4,17 @@ using System.Net.Sockets; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using SuperSocket.ProtoBase; using SuperSocket.Server; -using SuperSocket.Channel; - -namespace SuperSocket +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Connection; +using System.IO.Compression; + +namespace SuperSocket.Server.Host { public static class HostBuilderExtensions { @@ -133,5 +137,13 @@ public static IMinimalApiHostBuilder AsMinimalApiHostBuilder(this ISuperSocketHo { return hostBuilder; } + + public static ISuperSocketHostBuilder UseGZip(this ISuperSocketHostBuilder hostBuilder) + { + return hostBuilder.ConfigureServices((hostCtx, services) => + { + services.AddSingleton(new DefaultConnectionStreamInitializersFactory(CompressionLevel.Optimal)); + }) as ISuperSocketHostBuilder; + } } } diff --git a/src/SuperSocket.Server/Host/IServerHostBuilderAdapter.cs b/src/SuperSocket.Server/Host/IServerHostBuilderAdapter.cs new file mode 100644 index 000000000..37adbb4d9 --- /dev/null +++ b/src/SuperSocket.Server/Host/IServerHostBuilderAdapter.cs @@ -0,0 +1,13 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; + +namespace SuperSocket.Server.Host +{ + public interface IServerHostBuilderAdapter + { + void ConfigureServer(HostBuilderContext context, IServiceCollection hostServices); + + void ConfigureServiceProvider(IServiceProvider hostServiceProvider); + } +} \ No newline at end of file diff --git a/src/SuperSocket.Server/MultipleServerHostBuilder.cs b/src/SuperSocket.Server/Host/MultipleServerHostBuilder.cs similarity index 93% rename from src/SuperSocket.Server/MultipleServerHostBuilder.cs rename to src/SuperSocket.Server/Host/MultipleServerHostBuilder.cs index 3327a5b18..2518a908e 100644 --- a/src/SuperSocket.Server/MultipleServerHostBuilder.cs +++ b/src/SuperSocket.Server/Host/MultipleServerHostBuilder.cs @@ -6,10 +6,12 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using SuperSocket.Channel; using SuperSocket.ProtoBase; +using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; -namespace SuperSocket.Server +namespace SuperSocket.Server.Host { public class MultipleServerHostBuilder : HostBuilderAdapter, IMinimalApiHostBuilder { @@ -79,7 +81,7 @@ private ServerHostBuilderAdapter CreateServerHostBuilder(Action> hostBuilderDelegate) + public MultipleServerHostBuilder AddServer(Action> hostBuilderDelegate) where TReceivePackage : class { var hostBuilder = CreateServerHostBuilder(hostBuilderDelegate); @@ -87,7 +89,7 @@ public MultipleServerHostBuilder AddServer(Action(Action> hostBuilderDelegate) + public MultipleServerHostBuilder AddServer(Action> hostBuilderDelegate) where TReceivePackage : class where TPipelineFilter : IPipelineFilter, new() { diff --git a/src/SuperSocket.Server/ServerHostBuilderAdapter.cs b/src/SuperSocket.Server/Host/ServerHostBuilderAdapter.cs similarity index 96% rename from src/SuperSocket.Server/ServerHostBuilderAdapter.cs rename to src/SuperSocket.Server/Host/ServerHostBuilderAdapter.cs index fb95db6a8..cfd5dd44b 100644 --- a/src/SuperSocket.Server/ServerHostBuilderAdapter.cs +++ b/src/SuperSocket.Server/Host/ServerHostBuilderAdapter.cs @@ -5,16 +5,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; -namespace SuperSocket.Server +namespace SuperSocket.Server.Host { - public interface IServerHostBuilderAdapter - { - void ConfigureServer(HostBuilderContext context, IServiceCollection hostServices); - - void ConfigureServiceProvider(IServiceProvider hostServiceProvider); - } - public class ServerHostBuilderAdapter : SuperSocketHostBuilder, IServerHostBuilderAdapter { private IHostBuilder _hostBuilder; diff --git a/src/SuperSocket.Server/SuperSocketHostBuilder.cs b/src/SuperSocket.Server/Host/SuperSocketHostBuilder.cs similarity index 89% rename from src/SuperSocket.Server/SuperSocketHostBuilder.cs rename to src/SuperSocket.Server/Host/SuperSocketHostBuilder.cs index a041ce8e5..63129136c 100644 --- a/src/SuperSocket.Server/SuperSocketHostBuilder.cs +++ b/src/SuperSocket.Server/Host/SuperSocketHostBuilder.cs @@ -10,8 +10,14 @@ using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; - -namespace SuperSocket +using SuperSocket.Server.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; + +namespace SuperSocket.Server.Host { public class SuperSocketHostBuilder : HostBuilderAdapter>, ISuperSocketHostBuilder, IHostBuilder { @@ -113,6 +119,10 @@ protected virtual void RegisterDefaultServices(HostBuilderContext builderContext services.TryAdd(ServiceDescriptor.Singleton, DefaultStringEncoderForDI>()); services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd(ServiceDescriptor.Singleton(new SocketOptionsSetter(socket => {}))); + services.TryAdd(ServiceDescriptor.Singleton()); + services.TryAdd(ServiceDescriptor.Singleton()); // if no host service was defined, just use the default one if (!CheckIfExistHostedService(services)) @@ -182,6 +192,7 @@ public virtual ISuperSocketHostBuilder UsePipelineFilter { services.AddSingleton, DefaultPipelineFilterFactory>(); + services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService>() as IPipelineFilterFactory); }); } @@ -191,6 +202,7 @@ public virtual ISuperSocketHostBuilder UsePipelineFilterFactory return this.ConfigureServices((ctx, services) => { services.AddSingleton, TPipelineFilterFactory>(); + services.AddSingleton(serviceProvider => serviceProvider.GetRequiredService>() as IPipelineFilterFactory); }); } @@ -277,6 +289,11 @@ public ISuperSocketHostBuilder UsePackageHandlingContextAccesso } ); } + + public ISuperSocketHostBuilder UseGZip() + { + return (this as ISuperSocketHostBuilder).UseGZip() as ISuperSocketHostBuilder; + } } public static class SuperSocketHostBuilder diff --git a/src/SuperSocket.Server/IPackageHandlingContextAccessor.cs b/src/SuperSocket.Server/IPackageHandlingContextAccessor.cs index e25bc0176..96e2eb438 100644 --- a/src/SuperSocket.Server/IPackageHandlingContextAccessor.cs +++ b/src/SuperSocket.Server/IPackageHandlingContextAccessor.cs @@ -1,18 +1,9 @@ -using SuperSocket.Channel; -using SuperSocket.ProtoBase; -using System; -using System.Collections.Generic; -using System.Net; -using System.Text; -using System.Threading.Tasks; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { - public interface IPackageHandlingContextAccessor { PackageHandlingContext PackageHandlingContext { get; set; } } - - } diff --git a/src/SuperSocket.Server/ISessionEventHost.cs b/src/SuperSocket.Server/ISessionEventHost.cs deleted file mode 100644 index a5fee04f1..000000000 --- a/src/SuperSocket.Server/ISessionEventHost.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using SuperSocket.Channel; - -namespace SuperSocket.Server -{ - public interface ISessionEventHost - { - ValueTask HandleSessionConnectedEvent(AppSession session); - - ValueTask HandleSessionClosedEvent(AppSession session, CloseReason reason); - } -} \ No newline at end of file diff --git a/src/SuperSocket.Server/PackageHandlingContextAccessor.cs b/src/SuperSocket.Server/PackageHandlingContextAccessor.cs index f23ae7573..33dffa0f5 100644 --- a/src/SuperSocket.Server/PackageHandlingContextAccessor.cs +++ b/src/SuperSocket.Server/PackageHandlingContextAccessor.cs @@ -1,16 +1,14 @@ -using SuperSocket.Channel; -using SuperSocket.ProtoBase; +using SuperSocket.ProtoBase; using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { - - public class PackageHandlingContextAccessor : IPackageHandlingContextAccessor { private static AsyncLocal AppSessionCurrent { get; set; } = new AsyncLocal(); diff --git a/src/SuperSocket.Server/PackageHandlingSchedulerBase.cs b/src/SuperSocket.Server/PackageHandlingSchedulerBase.cs index 73ae98ba4..a7ff262ee 100644 --- a/src/SuperSocket.Server/PackageHandlingSchedulerBase.cs +++ b/src/SuperSocket.Server/PackageHandlingSchedulerBase.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/SerialPackageHandlingScheduler.cs b/src/SuperSocket.Server/SerialPackageHandlingScheduler.cs index adb0b6729..3f26a4c66 100644 --- a/src/SuperSocket.Server/SerialPackageHandlingScheduler.cs +++ b/src/SuperSocket.Server/SerialPackageHandlingScheduler.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/SessionHandlers.cs b/src/SuperSocket.Server/SessionHandlers.cs index ddcf5d943..91ee1121b 100644 --- a/src/SuperSocket.Server/SessionHandlers.cs +++ b/src/SuperSocket.Server/SessionHandlers.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using System.Net; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Server { diff --git a/src/SuperSocket.Server/SocketOptionsSetter.cs b/src/SuperSocket.Server/SocketOptionsSetter.cs index 76d1ff52b..55d302545 100644 --- a/src/SuperSocket.Server/SocketOptionsSetter.cs +++ b/src/SuperSocket.Server/SocketOptionsSetter.cs @@ -3,7 +3,7 @@ namespace SuperSocket.Server { - class SocketOptionsSetter + public class SocketOptionsSetter { public Action Setter { get; private set; } diff --git a/src/SuperSocket.Server/SuperSocket.Server.csproj b/src/SuperSocket.Server/SuperSocket.Server.csproj index d7c8692c6..059ea36de 100755 --- a/src/SuperSocket.Server/SuperSocket.Server.csproj +++ b/src/SuperSocket.Server/SuperSocket.Server.csproj @@ -7,8 +7,7 @@ - - + diff --git a/src/SuperSocket.Server/SuperSocketExtensions.cs b/src/SuperSocket.Server/SuperSocketExtensions.cs index 69c3ca13b..dc573d861 100644 --- a/src/SuperSocket.Server/SuperSocketExtensions.cs +++ b/src/SuperSocket.Server/SuperSocketExtensions.cs @@ -12,6 +12,10 @@ using System.Net; using System.Net.Sockets; using Microsoft.Extensions.Logging; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Host; namespace SuperSocket { @@ -24,7 +28,7 @@ public static async ValueTask ActiveConnect(this IServer server, EndPoint try { await socket.ConnectAsync(remoteEndpoint); - await (server as IChannelRegister).RegisterChannel(socket); + await (server as IConnectionRegister).RegisterConnection(socket); return true; } catch (Exception e) diff --git a/src/SuperSocket.Server/SuperSocketService.cs b/src/SuperSocket.Server/SuperSocketService.cs index fa09a18e4..abfeb056a 100644 --- a/src/SuperSocket.Server/SuperSocketService.cs +++ b/src/SuperSocket.Server/SuperSocketService.cs @@ -8,12 +8,17 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using static SuperSocket.Extensions; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Abstractions.Middleware; +using SuperSocket.Server.Connection; namespace SuperSocket.Server { - public class SuperSocketService : IHostedService, IServer, IChannelRegister, ILoggerAccessor, ISessionEventHost + public class SuperSocketService : ISuperSocketHostedService { private readonly IServiceProvider _serviceProvider; @@ -37,8 +42,8 @@ ILogger ILoggerAccessor.Logger } private IPipelineFilterFactory _pipelineFilterFactory; - private IChannelCreatorFactory _channelCreatorFactory; - private List _channelCreators; + private IConnectionListenerFactory _connectionListenerFactory; + private List _connectionListeners; private IPackageHandlingScheduler _packageHandlingScheduler; private IPackageHandlingContextAccessor _packageHandlingContextAccessor; @@ -82,7 +87,7 @@ public SuperSocketService(IServiceProvider serviceProvider, IOptions(); _logger = _loggerFactory.CreateLogger("SuperSocketService"); - _channelCreatorFactory = serviceProvider.GetService() ?? new TcpChannelCreatorFactory(serviceProvider); + _connectionListenerFactory = serviceProvider.GetService(); _sessionHandlers = serviceProvider.GetService(); _sessionFactory = serviceProvider.GetService(); _packageHandlingContextAccessor = serviceProvider.GetService>(); @@ -98,7 +103,7 @@ public SuperSocketService(IServiceProvider serviceProvider, IOptions, ValueTask>>() - ?? OnSessionErrorAsync; + ?? OnSessionErrorAsync; _packageHandlingScheduler = serviceProvider.GetService>() ?? new SerialPackageHandlingScheduler(); @@ -111,10 +116,10 @@ protected virtual IPipelineFilterFactory GetPipelineFilterF return _serviceProvider.GetRequiredService>(); } - private bool AddChannelCreator(ListenOptions listenOptions, ServerOptions serverOptions) + private bool AddConnectionListener(ListenOptions listenOptions, ServerOptions serverOptions) { - var listener = _channelCreatorFactory.CreateChannelCreator(listenOptions, serverOptions, _loggerFactory, _pipelineFilterFactory); - listener.NewClientAccepted += OnNewClientAccept; + var listener = _connectionListenerFactory.CreateConnectionListener(listenOptions, serverOptions, _loggerFactory, _pipelineFilterFactory); + listener.NewConnectionAccept += OnNewConnectionAccept; if (!listener.Start()) { @@ -123,13 +128,13 @@ private bool AddChannelCreator(ListenOptions listenOptions, ServerOptions server } _logger.LogInformation($"The listener [{listener}] has been started."); - _channelCreators.Add(listener); + _connectionListeners.Add(listener); return true; } private Task StartListenAsync(CancellationToken cancellationToken) { - _channelCreators = new List(); + _connectionListeners = new List(); var serverOptions = Options; @@ -140,7 +145,7 @@ private Task StartListenAsync(CancellationToken cancellationToken) if (cancellationToken.IsCancellationRequested) break; - if (!AddChannelCreator(l, serverOptions)) + if (!AddConnectionListener(l, serverOptions)) { continue; } @@ -150,31 +155,33 @@ private Task StartListenAsync(CancellationToken cancellationToken) { _logger.LogWarning("No listener was defined, so this server only can accept connections from the ActiveConnect."); - if (!AddChannelCreator(null, serverOptions)) + if (!AddConnectionListener(null, serverOptions)) { _logger.LogError($"Failed to add the channel creator."); return Task.FromResult(false); } } - return Task.FromResult(_channelCreators.Any()); + return Task.FromResult(_connectionListeners.Any()); } - protected virtual ValueTask OnNewClientAccept(IChannelCreator listener, IChannel channel) + protected virtual ValueTask OnNewConnectionAccept(ListenOptions listenOptions, IConnection connection) { - return AcceptNewChannel(channel); + return AcceptNewConnection(connection); } - private ValueTask AcceptNewChannel(IChannel channel) + private ValueTask AcceptNewConnection(IConnection connection) { var session = _sessionFactory.Create() as AppSession; - return HandleSession(session, channel); + return HandleSession(session, connection); } - async Task IChannelRegister.RegisterChannel(object connection) + async Task IConnectionRegister.RegisterConnection(object connectionSource) { - var channel = await _channelCreators.FirstOrDefault().CreateChannel(connection); - await AcceptNewChannel(channel); + var connectionListener = _connectionListeners.FirstOrDefault(); + using var cts = new CancellationTokenSource(connectionListener.Options.ConnectionAcceptTimeOut); + var connection = await connectionListener.ConnectionFactory.CreateConnection(connectionSource, cts.Token); + await AcceptNewConnection(connection); } protected virtual object CreatePipelineContext(IAppSession session) @@ -259,13 +266,13 @@ private async ValueTask UnRegisterSessionFromMiddlewares(IAppSession session) #endregion - private async ValueTask InitializeSession(IAppSession session, IChannel channel) + private async ValueTask InitializeSession(IAppSession session, IConnection connection) { - session.Initialize(this, channel); + session.Initialize(this, connection); - if (channel is IPipeChannel pipeChannel) + if (connection is IPipeConnection pipeConnection) { - pipeChannel.PipelineFilter.Context = CreatePipelineContext(session); + pipeConnection.PipelineFilter.Context = CreatePipelineContext(session); } var middlewares = _middlewares; @@ -281,7 +288,7 @@ private async ValueTask InitializeSession(IAppSession session, IChannel ch return false; } - channel.Closed += (s, e) => OnChannelClosed(session, e); + connection.Closed += (s, e) => OnChannelClosed(session, e); return true; } @@ -363,31 +370,31 @@ protected virtual async ValueTask FireSessionClosedEvent(AppSession session, Clo } } - ValueTask ISessionEventHost.HandleSessionConnectedEvent(AppSession session) + ValueTask ISessionEventHost.HandleSessionConnectedEvent(IAppSession session) { - return FireSessionConnectedEvent(session); + return FireSessionConnectedEvent((AppSession)session); } - ValueTask ISessionEventHost.HandleSessionClosedEvent(AppSession session, CloseReason reason) + ValueTask ISessionEventHost.HandleSessionClosedEvent(IAppSession session, CloseReason reason) { - return FireSessionClosedEvent(session, reason); + return FireSessionClosedEvent((AppSession)session, reason); } - private async ValueTask HandleSession(AppSession session, IChannel channel) + private async ValueTask HandleSession(AppSession session, IConnection connection) { - if (!await InitializeSession(session, channel)) + if (!await InitializeSession(session, connection)) return; try { - channel.Start(); + connection.Start(); await FireSessionConnectedEvent(session); - var packageChannel = channel as IChannel; + var packageConnection = connection as IConnection; var packageHandlingScheduler = _packageHandlingScheduler; - await foreach (var p in packageChannel.RunAsync()) + await foreach (var p in packageConnection.RunAsync()) { if(_packageHandlingContextAccessor != null) { @@ -456,7 +463,7 @@ protected virtual ValueTask OnStopAsync() #endif } - private async Task StopListener(IChannelCreator listener) + private async Task StopListener(IConnectionListener listener) { await listener.StopAsync().ConfigureAwait(false); _logger.LogInformation($"The listener [{listener}] has been stopped."); @@ -473,7 +480,7 @@ public async Task StopAsync(CancellationToken cancellationToken) _state = ServerState.Stopping; - var tasks = _channelCreators.Where(l => l.IsRunning).Select(l => StopListener(l)) + var tasks = _connectionListeners.Where(l => l.IsRunning).Select(l => StopListener(l)) .Union(new Task[] { Task.Run(ShutdownMiddlewares) }); await Task.WhenAll(tasks).ConfigureAwait(false); diff --git a/src/SuperSocket.Server/TcpChannelCreatorFactory.cs b/src/SuperSocket.Server/TcpChannelCreatorFactory.cs deleted file mode 100644 index 5284d8eb9..000000000 --- a/src/SuperSocket.Server/TcpChannelCreatorFactory.cs +++ /dev/null @@ -1,124 +0,0 @@ -using System; -using System.Net.Security; -using System.Net.Sockets; -using System.Security.Authentication; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.DependencyInjection; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; - -namespace SuperSocket.Server -{ - public class TcpChannelCreatorFactory : IChannelCreatorFactory - { - private Action _socketOptionsSetter; - - public TcpChannelCreatorFactory(IServiceProvider serviceProvider) - { - _socketOptionsSetter = serviceProvider.GetService()?.Setter; - } - - protected virtual void ApplySocketOptions(Socket socket, ListenOptions listenOptions, ChannelOptions channelOptions, ILogger logger) - { - try - { - if (listenOptions.NoDelay) - socket.NoDelay = true; - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to set NoDelay for the socket."); - } - - try - { - if (channelOptions.ReceiveBufferSize > 0) - socket.ReceiveBufferSize = channelOptions.ReceiveBufferSize; - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to set ReceiveBufferSize for the socket."); - } - - try - { - if (channelOptions.SendBufferSize > 0) - socket.SendBufferSize = channelOptions.SendBufferSize; - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to set SendBufferSize for the socket."); - } - - try - { - if (channelOptions.ReceiveTimeout > 0) - socket.ReceiveTimeout = channelOptions.ReceiveTimeout; - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to set ReceiveTimeout for the socket."); - } - - try - { - if (channelOptions.SendTimeout > 0) - socket.SendTimeout = channelOptions.SendTimeout; - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to set SendTimeout for the socket."); - } - - try - { - _socketOptionsSetter?.Invoke(socket); - } - catch (Exception e) - { - logger.LogWarning(e, "Failed to run socketOptionSetter for the socket."); - } - } - - public IChannelCreator CreateChannelCreator(ListenOptions options, ChannelOptions channelOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory) - { - var filterFactory = pipelineFilterFactory as IPipelineFilterFactory; - channelOptions.Logger = loggerFactory.CreateLogger(nameof(IChannel)); - - var channelFactoryLogger = loggerFactory.CreateLogger(nameof(TcpChannelCreator)); - - if (options.Security == SslProtocols.None) - { - return new TcpChannelCreator(options, (s) => - { - ApplySocketOptions(s, options, channelOptions, channelFactoryLogger); - return new ValueTask((new TcpPipeChannel(s, filterFactory.Create(s), channelOptions)) as IChannel); - }, channelFactoryLogger); - } - else - { - var channelFactory = new Func>(async (s) => - { - ApplySocketOptions(s, options, channelOptions, channelFactoryLogger); - - var authOptions = new SslServerAuthenticationOptions(); - - authOptions.EnabledSslProtocols = options.Security; - authOptions.ServerCertificate = options.CertificateOptions.Certificate; - authOptions.ClientCertificateRequired = options.CertificateOptions.ClientCertificateRequired; - - if (options.CertificateOptions.RemoteCertificateValidationCallback != null) - authOptions.RemoteCertificateValidationCallback = options.CertificateOptions.RemoteCertificateValidationCallback; - - var stream = new SslStream(new NetworkStream(s, true), false); - await stream.AuthenticateAsServerAsync(authOptions, CancellationToken.None).ConfigureAwait(false); - return new SslStreamPipeChannel(stream, s.RemoteEndPoint, s.LocalEndPoint, filterFactory.Create(s), channelOptions); - }); - - return new TcpChannelCreator(options, channelFactory, channelFactoryLogger); - } - } - } -} \ No newline at end of file diff --git a/src/SuperSocket.SessionContainer/SuperSocket.SessionContainer.csproj b/src/SuperSocket.SessionContainer/SuperSocket.SessionContainer.csproj deleted file mode 100644 index 62954fb14..000000000 --- a/src/SuperSocket.SessionContainer/SuperSocket.SessionContainer.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - SuperSocket built-in session containers. - - - - - - diff --git a/src/SuperSocket.Udp/IPAddressUdpSessionIdentifierProvider.cs b/src/SuperSocket.Udp/IPAddressUdpSessionIdentifierProvider.cs index f27082549..732836a78 100644 --- a/src/SuperSocket.Udp/IPAddressUdpSessionIdentifierProvider.cs +++ b/src/SuperSocket.Udp/IPAddressUdpSessionIdentifierProvider.cs @@ -1,10 +1,4 @@ using System; -using System.Buffers; -using System.Threading.Tasks; -using System.Threading; -using System.Net.Sockets; -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; using System.Net; namespace SuperSocket.Udp diff --git a/src/SuperSocket.Udp/IUdpSessionIdentifierProvider.cs b/src/SuperSocket.Udp/IUdpSessionIdentifierProvider.cs index 349e1951d..99fea3391 100644 --- a/src/SuperSocket.Udp/IUdpSessionIdentifierProvider.cs +++ b/src/SuperSocket.Udp/IUdpSessionIdentifierProvider.cs @@ -1,10 +1,4 @@ using System; -using System.Buffers; -using System.Threading.Tasks; -using System.Threading; -using System.Net.Sockets; -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; using System.Net; namespace SuperSocket.Udp diff --git a/src/SuperSocket.Udp/SuperSocket.Udp.csproj b/src/SuperSocket.Udp/SuperSocket.Udp.csproj index dffbb2843..47a6efb25 100644 --- a/src/SuperSocket.Udp/SuperSocket.Udp.csproj +++ b/src/SuperSocket.Udp/SuperSocket.Udp.csproj @@ -4,6 +4,7 @@ - + + \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpChannelCreatorFactory.cs b/src/SuperSocket.Udp/UdpChannelCreatorFactory.cs deleted file mode 100644 index 5daa66f94..000000000 --- a/src/SuperSocket.Udp/UdpChannelCreatorFactory.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Buffers; -using System.Net; -using System.Net.Sockets; -using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using SuperSocket.Channel; -using SuperSocket.ProtoBase; - -namespace SuperSocket.Udp -{ - class UdpChannelCreatorFactory : IChannelCreatorFactory - { - private readonly IUdpSessionIdentifierProvider _udpSessionIdentifierProvider; - - private readonly IAsyncSessionContainer _sessionContainer; - - public UdpChannelCreatorFactory(IUdpSessionIdentifierProvider udpSessionIdentifierProvider, IAsyncSessionContainer sessionContainer) - { - _udpSessionIdentifierProvider = udpSessionIdentifierProvider; - _sessionContainer = sessionContainer; - } - - public IChannelCreator CreateChannelCreator(ListenOptions options, ChannelOptions channelOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory) - { - var filterFactory = pipelineFilterFactory as IPipelineFilterFactory; - channelOptions.Logger = loggerFactory.CreateLogger(nameof(IChannel)); - var channelFactoryLogger = loggerFactory.CreateLogger(nameof(UdpChannelCreator)); - - var channelFactory = new Func>((s, re, id) => - { - var filter = filterFactory.Create(s); - return new ValueTask(new UdpPipeChannel(s, filter, channelOptions, re, id)); - }); - - return new UdpChannelCreator(options, channelOptions, channelFactory, channelFactoryLogger, _udpSessionIdentifierProvider, _sessionContainer); - } - } -} \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpConnectionFactory.cs b/src/SuperSocket.Udp/UdpConnectionFactory.cs new file mode 100644 index 000000000..c0e729cdd --- /dev/null +++ b/src/SuperSocket.Udp/UdpConnectionFactory.cs @@ -0,0 +1,28 @@ +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Connection; +using SuperSocket.ProtoBase; + +namespace SuperSocket.Udp +{ + public class UdpConnectionFactory : IConnectionFactory + { + protected IPipelineFilterFactory PipelineFilterFactory; + + public UdpConnectionFactory(IPipelineFilterFactory pipelineFilterFactory) + { + this.PipelineFilterFactory = pipelineFilterFactory; + } + + public Task CreateConnection(object connection, CancellationToken cancellationToken) + { + var connectionInfo = (UdpConnectionInfo)connection; + + var filter = PipelineFilterFactory.Create(connectionInfo.Socket); + + return Task.FromResult(new UdpPipeConnection(connectionInfo.Socket, filter, connectionInfo.ConnectionOptions, connectionInfo.RemoteEndPoint, connectionInfo.SessionIdentifier)); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpConnectionFactoryBuilder.cs b/src/SuperSocket.Udp/UdpConnectionFactoryBuilder.cs new file mode 100644 index 000000000..b1720c943 --- /dev/null +++ b/src/SuperSocket.Udp/UdpConnectionFactoryBuilder.cs @@ -0,0 +1,24 @@ +using System; +using System.Net; +using SuperSocket.Connection; +using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; + +namespace SuperSocket.Udp +{ + public class UdpConnectionFactoryBuilder : IConnectionFactoryBuilder + { + public IPipelineFilterFactory PipelineFilterFactory { get; } + + public UdpConnectionFactoryBuilder(IPipelineFilterFactory pipelineFilterFactory) + { + PipelineFilterFactory = pipelineFilterFactory; + } + + public IConnectionFactory Build(ListenOptions listenOptions, ConnectionOptions connectionOptions) + { + return new UdpConnectionFactory(PipelineFilterFactory as IPipelineFilterFactory); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpConnectionInfo.cs b/src/SuperSocket.Udp/UdpConnectionInfo.cs new file mode 100644 index 000000000..2fe25bb27 --- /dev/null +++ b/src/SuperSocket.Udp/UdpConnectionInfo.cs @@ -0,0 +1,18 @@ +using System; +using System.Net; +using System.Net.Sockets; +using SuperSocket.Connection; + +namespace SuperSocket.Udp +{ + internal struct UdpConnectionInfo + { + public Socket Socket { get; set; } + + public ConnectionOptions ConnectionOptions{ get; set; } + + public string SessionIdentifier { get; set; } + + public IPEndPoint RemoteEndPoint { get; set; } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpChannelCreator.cs b/src/SuperSocket.Udp/UdpConnectionListener.cs similarity index 71% rename from src/SuperSocket.Udp/UdpChannelCreator.cs rename to src/SuperSocket.Udp/UdpConnectionListener.cs index be38b3995..c9db3a650 100644 --- a/src/SuperSocket.Udp/UdpChannelCreator.cs +++ b/src/SuperSocket.Udp/UdpConnectionListener.cs @@ -5,11 +5,14 @@ using System.Net; using System.Net.Sockets; using Microsoft.Extensions.Logging; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Udp { - class UdpChannelCreator : IChannelCreator + class UdpConnectionListener : IConnectionListener { private ILogger _logger; @@ -17,15 +20,15 @@ class UdpChannelCreator : IChannelCreator private IPEndPoint _acceptRemoteEndPoint; - private readonly Func> _channelFactory; + public IConnectionFactory ConnectionFactory { get; } public ListenOptions Options { get; } - public ChannelOptions ChannelOptions { get; } + public ConnectionOptions ConnectionOptions { get; } public bool IsRunning { get; private set; } - public event NewClientAcceptHandler NewClientAccepted; + public event NewConnectionAcceptHandler NewConnectionAccept; private static readonly ArrayPool _bufferPool = ArrayPool.Shared; @@ -37,11 +40,11 @@ class UdpChannelCreator : IChannelCreator private IAsyncSessionContainer _sessionContainer; - public UdpChannelCreator(ListenOptions options, ChannelOptions channelOptions, Func> channelFactory, ILogger logger, IUdpSessionIdentifierProvider udpSessionIdentifierProvider, IAsyncSessionContainer sessionContainer) + public UdpConnectionListener(ListenOptions options, ConnectionOptions connectionOptions, IConnectionFactory connectionFactory, ILogger logger, IUdpSessionIdentifierProvider udpSessionIdentifierProvider, IAsyncSessionContainer sessionContainer) { Options = options; - ChannelOptions = channelOptions; - _channelFactory = channelFactory; + ConnectionOptions = connectionOptions; + ConnectionFactory = connectionFactory; _logger = logger; _udpSessionIdentifierProvider = udpSessionIdentifierProvider; _sessionContainer = sessionContainer; @@ -53,7 +56,7 @@ public bool Start() try { - var listenEndpoint = options.GetListenEndPoint(); + var listenEndpoint = options.ToEndPoint(); var listenSocket = _listenSocket = new Socket(listenEndpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); if (options.NoDelay) @@ -101,7 +104,7 @@ private async Task KeepAccept(Socket listenSocket) try { - var bufferSize = ChannelOptions.MaxPackageLength; + var bufferSize = ConnectionOptions.MaxPackageLength; buffer = _bufferPool.Rent(bufferSize); var result = await listenSocket @@ -115,23 +118,23 @@ private async Task KeepAccept(Socket listenSocket) var session = await _sessionContainer.GetSessionByIDAsync(sessionID); - IVirtualChannel channel = null; + IVirtualConnection connection = null; if (session != null) { - channel = session.Channel as IVirtualChannel; + connection = session.Connection as IVirtualConnection; } else { - channel = await CreateChannel(_listenSocket, remoteEndPoint, sessionID); + connection = await CreateConnection(_listenSocket, remoteEndPoint, sessionID) as IVirtualConnection; - if (channel == null) + if (connection == null) return; - OnNewClientAccept(channel); + OnNewConnectionAccept(connection); } - await channel.WritePipeDataAsync(packageData.AsMemory(), _cancellationTokenSource.Token); + await connection.WritePipeDataAsync(packageData.AsMemory(), _cancellationTokenSource.Token); } catch (Exception e) { @@ -160,21 +163,28 @@ private async Task KeepAccept(Socket listenSocket) _stopTaskCompletionSource.TrySetResult(true); } - private void OnNewClientAccept(IChannel channel) + private void OnNewConnectionAccept(IConnection connection) { - var handler = NewClientAccepted; + var handler = NewConnectionAccept; if (handler == null) return; - handler.Invoke(this, channel); + handler.Invoke(Options, connection); } - private async ValueTask CreateChannel(Socket socket, IPEndPoint remoteEndPoint, string sessionIdentifier) + private async ValueTask CreateConnection(Socket socket, IPEndPoint remoteEndPoint, string sessionIdentifier) { try { - return await _channelFactory(socket, remoteEndPoint, sessionIdentifier); + using var cts = new CancellationTokenSource(Options.ConnectionAcceptTimeOut); + return await ConnectionFactory.CreateConnection(new UdpConnectionInfo + { + Socket = socket, + SessionIdentifier = sessionIdentifier, + RemoteEndPoint = remoteEndPoint, + ConnectionOptions = ConnectionOptions + }, cts.Token); } catch (Exception e) { @@ -183,11 +193,11 @@ private async ValueTask CreateChannel(Socket socket, IPEndPoint } } - public async Task CreateChannel(object connection) + public async Task CreateConnection(object connection) { var socket = (Socket)connection; var remoteEndPoint = socket.RemoteEndPoint as IPEndPoint; - return await CreateChannel(socket, remoteEndPoint, _udpSessionIdentifierProvider.GetSessionIdentifier(remoteEndPoint, null)); + return await CreateConnection(socket, remoteEndPoint, _udpSessionIdentifierProvider.GetSessionIdentifier(remoteEndPoint, null)); } public Task StopAsync() diff --git a/src/SuperSocket.Udp/UdpConnectionListenerFactory.cs b/src/SuperSocket.Udp/UdpConnectionListenerFactory.cs new file mode 100644 index 000000000..4f645e6fc --- /dev/null +++ b/src/SuperSocket.Udp/UdpConnectionListenerFactory.cs @@ -0,0 +1,41 @@ +using System; +using System.Buffers; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using SuperSocket.Connection; +using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; + +namespace SuperSocket.Udp +{ + class UdpConnectionListenerFactory : IConnectionListenerFactory + { + private readonly IConnectionFactoryBuilder _connectionFactoryBuilder; + + private readonly IUdpSessionIdentifierProvider _udpSessionIdentifierProvider; + + private readonly IAsyncSessionContainer _sessionContainer; + + public UdpConnectionListenerFactory(IConnectionFactoryBuilder connectionFactoryBuilder, IUdpSessionIdentifierProvider udpSessionIdentifierProvider, IAsyncSessionContainer sessionContainer) + { + _connectionFactoryBuilder = connectionFactoryBuilder; + _udpSessionIdentifierProvider = udpSessionIdentifierProvider; + _sessionContainer = sessionContainer; + } + + public IConnectionListener CreateConnectionListener(ListenOptions options, ConnectionOptions connectionOptions, ILoggerFactory loggerFactory, object pipelineFilterFactory) + { + var filterFactory = pipelineFilterFactory as IPipelineFilterFactory; + connectionOptions.Logger = loggerFactory.CreateLogger(nameof(IConnection)); + var connectionFactoryLogger = loggerFactory.CreateLogger(nameof(UdpConnectionFactory)); + + var connectionFactory = _connectionFactoryBuilder.Build(options, connectionOptions); + + return new UdpConnectionListener(options, connectionOptions, connectionFactory, connectionFactoryLogger, _udpSessionIdentifierProvider, _sessionContainer); + } + } +} \ No newline at end of file diff --git a/src/SuperSocket.Udp/UdpServerHostBuilderExtensions.cs b/src/SuperSocket.Udp/UdpServerHostBuilderExtensions.cs index 7d86edee7..efcbf076d 100644 --- a/src/SuperSocket.Udp/UdpServerHostBuilderExtensions.cs +++ b/src/SuperSocket.Udp/UdpServerHostBuilderExtensions.cs @@ -2,7 +2,12 @@ using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using SuperSocket.SessionContainer; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Middleware; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Udp; @@ -10,16 +15,12 @@ namespace SuperSocket { public static class UdpServerHostBuilderExtensions { - public static ISuperSocketHostBuilder UseUdp(this ISuperSocketHostBuilder hostBuilder) - { - return (hostBuilder as ISuperSocketHostBuilder).UseUdp() as ISuperSocketHostBuilder; - } - public static ISuperSocketHostBuilder UseUdp(this ISuperSocketHostBuilder hostBuilder) { return (hostBuilder.ConfigureServices((context, services) => { - services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); }) as ISuperSocketHostBuilder) .ConfigureSupplementServices((context, services) => { @@ -37,5 +38,10 @@ public static ISuperSocketHostBuilder UseUdp(this ISuperSocketHostBuilder hostBu } }); } + + public static ISuperSocketHostBuilder UseUdp(this ISuperSocketHostBuilder hostBuilder) + { + return (hostBuilder as ISuperSocketHostBuilder).UseUdp() as ISuperSocketHostBuilder; + } } } \ No newline at end of file diff --git a/src/SuperSocket.WebSocket.Server/CommandSubProtocolHandler.cs b/src/SuperSocket.WebSocket.Server/CommandSubProtocolHandler.cs index 7ef86ba33..4cc3b1943 100644 --- a/src/SuperSocket.WebSocket.Server/CommandSubProtocolHandler.cs +++ b/src/SuperSocket.WebSocket.Server/CommandSubProtocolHandler.cs @@ -6,7 +6,8 @@ using Microsoft.Extensions.Options; using SuperSocket.Command; using SuperSocket.ProtoBase; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.WebSocket.Server { diff --git a/src/SuperSocket.WebSocket.Server/DelegateSubProtocolHandler.cs b/src/SuperSocket.WebSocket.Server/DelegateSubProtocolHandler.cs index 62faf9544..b1c658645 100644 --- a/src/SuperSocket.WebSocket.Server/DelegateSubProtocolHandler.cs +++ b/src/SuperSocket.WebSocket.Server/DelegateSubProtocolHandler.cs @@ -1,9 +1,6 @@ using System; -using System.Linq; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.WebSocket.Server { diff --git a/src/SuperSocket.WebSocket.Server/ISubProtocolHandler.cs b/src/SuperSocket.WebSocket.Server/ISubProtocolHandler.cs index e351e36fb..ffaf654ca 100644 --- a/src/SuperSocket.WebSocket.Server/ISubProtocolHandler.cs +++ b/src/SuperSocket.WebSocket.Server/ISubProtocolHandler.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions; namespace SuperSocket.WebSocket.Server { diff --git a/src/SuperSocket.WebSocket.Server/SubProtocolHandlerBase.cs b/src/SuperSocket.WebSocket.Server/SubProtocolHandlerBase.cs index 452deece7..368479d04 100644 --- a/src/SuperSocket.WebSocket.Server/SubProtocolHandlerBase.cs +++ b/src/SuperSocket.WebSocket.Server/SubProtocolHandlerBase.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.WebSocket.Server { diff --git a/src/SuperSocket.WebSocket.Server/WebSocketCommandMiddleware.cs b/src/SuperSocket.WebSocket.Server/WebSocketCommandMiddleware.cs index 71a536e48..14fea7a3b 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketCommandMiddleware.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketCommandMiddleware.cs @@ -1,11 +1,8 @@ using System; -using System.Collections.Specialized; -using System.Threading.Tasks; using Microsoft.Extensions.Options; -using SuperSocket.Channel; +using SuperSocket.Server.Abstractions.Middleware; using SuperSocket.Command; using SuperSocket.ProtoBase; -using SuperSocket.Server; namespace SuperSocket.WebSocket.Server { diff --git a/src/SuperSocket.WebSocket.Server/WebSocketHostBuilder.cs b/src/SuperSocket.WebSocket.Server/WebSocketHostBuilder.cs index 5e4ad31b5..3ac114b40 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketHostBuilder.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketHostBuilder.cs @@ -3,7 +3,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using SuperSocket.Server; -using SuperSocket.ProtoBase; +using SuperSocket.Server.Connection; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.WebSocket.Server { @@ -24,6 +28,10 @@ public WebSocketHostBuilderAdapter(IHostBuilder hostBuilder) protected override void RegisterDefaultServices(HostBuilderContext builderContext, IServiceCollection servicesInHost, IServiceCollection services) { services.TryAddSingleton>(); + services.TryAddSingleton(); + services.TryAddSingleton(new SocketOptionsSetter(socket => { })); + services.TryAddSingleton(); + services.TryAddSingleton(); } } diff --git a/src/SuperSocket.WebSocket.Server/WebSocketHostBuilderExtensions.cs b/src/SuperSocket.WebSocket.Server/WebSocketHostBuilderExtensions.cs index 7bbc13d90..75cc80a86 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketHostBuilderExtensions.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketHostBuilderExtensions.cs @@ -7,6 +7,8 @@ using Microsoft.Extensions.Options; using SuperSocket.Command; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.WebSocket.Server.Extensions; using SuperSocket.WebSocket.Server.Extensions.Compression; diff --git a/src/SuperSocket.WebSocket.Server/WebSocketPackageHandler.cs b/src/SuperSocket.WebSocket.Server/WebSocketPackageHandler.cs index 9a1ef0383..9d829e851 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketPackageHandler.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketPackageHandler.cs @@ -10,10 +10,10 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.WebSocket.Extensions; using SuperSocket.WebSocket.Server.Extensions; @@ -334,7 +334,7 @@ private async ValueTask HandleHandshake(IAppSession session, WebSocketPack if (selectedExtensionHeadItems != null && selectedExtensionHeadItems.Count > 0) { - var pipeChannel = session.Channel as IPipeChannel; + var pipeChannel = session.Connection as IPipeConnection; pipeChannel.PipelineFilter.Context = new WebSocketPipelineFilterContext { Extensions = extensions @@ -363,7 +363,7 @@ private async ValueTask HandleHandshake(IAppSession session, WebSocketPack var encoding = _textEncoding; - await session.Channel.SendAsync((writer) => + await session.Connection.SendAsync((writer) => { writer.Write(WebSocketConstant.ResponseHeadLine10, encoding); writer.Write(WebSocketConstant.ResponseUpgradeLine, encoding); diff --git a/src/SuperSocket.WebSocket.Server/WebSocketServerMiddleware.cs b/src/SuperSocket.WebSocket.Server/WebSocketServerMiddleware.cs index dc665fefd..61c207953 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketServerMiddleware.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketServerMiddleware.cs @@ -4,6 +4,9 @@ using System.Threading.Tasks; using Microsoft.Extensions.Options; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Middleware; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.WebSocket.Server { @@ -94,7 +97,7 @@ private void HandshakePendingQueueCheckingCallback(object state) if (!_openHandshakePendingQueue.TryPeek(out session)) break; - if (session.Handshaked || session.State == SessionState.Closed || (session is IAppSession appSession && appSession.Channel.IsClosed)) + if (session.Handshaked || session.State == SessionState.Closed || (session is IAppSession appSession && appSession.Connection.IsClosed)) { //Handshaked or not connected _openHandshakePendingQueue.TryDequeue(out session); diff --git a/src/SuperSocket.WebSocket.Server/WebSocketSession.cs b/src/SuperSocket.WebSocket.Server/WebSocketSession.cs index b7b33fdf5..b3912348b 100644 --- a/src/SuperSocket.WebSocket.Server/WebSocketSession.cs +++ b/src/SuperSocket.WebSocket.Server/WebSocketSession.cs @@ -5,7 +5,8 @@ using System.Threading.Tasks; using SuperSocket.ProtoBase; using SuperSocket.Server; -using ChannelCloseReason = SuperSocket.Channel.CloseReason; +using SuperSocket.Server.Abstractions.Session; +using ChannelCloseReason = SuperSocket.Connection.CloseReason; namespace SuperSocket.WebSocket.Server { @@ -34,7 +35,7 @@ public string Path public virtual ValueTask SendAsync(WebSocketPackage message) { - return this.Channel.SendAsync(MessageEncoder, message); + return this.Connection.SendAsync(MessageEncoder, message); } public virtual ValueTask SendAsync(string message) diff --git a/test/SuperSocket.Benchmarks/CurrentSend.cs b/test/SuperSocket.Benchmarks/CurrentSend.cs index 2ae95893e..883825b8a 100644 --- a/test/SuperSocket.Benchmarks/CurrentSend.cs +++ b/test/SuperSocket.Benchmarks/CurrentSend.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using BenchmarkDotNet; using BenchmarkDotNet.Attributes; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Benchmarks @@ -27,15 +27,15 @@ public async Task SendTest() for (var i = 0; i < ConcurrentLevel; i++) { - tasks[i] = Send(pool, new ChannelOptions(), Iteration); + tasks[i] = Send(pool, new ConnectionOptions(), Iteration); } await Task.WhenAll(tasks); } - private async Task Send(ArrayPool pool, ChannelOptions options, int iteration) + private async Task Send(ArrayPool pool, ConnectionOptions options, int iteration) { - var channel = new TransparentPipeChannel(new CommandLinePipelineFilter(), options); + var channel = new TransparentPipeConnection(new CommandLinePipelineFilter(), options); channel.Start(); for (var i = 0; i < iteration; i++) diff --git a/test/SuperSocket.Benchmarks/SuperSocket.Benchmarks.csproj b/test/SuperSocket.Benchmarks/SuperSocket.Benchmarks.csproj index 83eaa3880..56f2a9147 100644 --- a/test/SuperSocket.Benchmarks/SuperSocket.Benchmarks.csproj +++ b/test/SuperSocket.Benchmarks/SuperSocket.Benchmarks.csproj @@ -8,6 +8,6 @@ - + diff --git a/test/SuperSocket.Benchmarks/TransparentPipeChannel.cs b/test/SuperSocket.Benchmarks/TransparentPipeConnection.cs similarity index 81% rename from test/SuperSocket.Benchmarks/TransparentPipeChannel.cs rename to test/SuperSocket.Benchmarks/TransparentPipeConnection.cs index 4a373b23d..9ef9c5e1d 100644 --- a/test/SuperSocket.Benchmarks/TransparentPipeChannel.cs +++ b/test/SuperSocket.Benchmarks/TransparentPipeConnection.cs @@ -2,17 +2,17 @@ using System.Buffers; using System.Threading; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Benchmarks { - public class TransparentPipeChannel : PipeChannel + public class TransparentPipeConnection : PipeConnection { private TaskCompletionSource _tcs; private Task _channelTask; - public TransparentPipeChannel(IPipelineFilter pipelineFilter, ChannelOptions options) + public TransparentPipeConnection(IPipelineFilter pipelineFilter, ConnectionOptions options) : base(pipelineFilter, options) { _tcs = new TaskCompletionSource(); diff --git a/test/SuperSocket.Tests.Command/MIN.cs b/test/SuperSocket.Tests.Command/MIN.cs index 2bd3575f4..11946546a 100644 --- a/test/SuperSocket.Tests.Command/MIN.cs +++ b/test/SuperSocket.Tests.Command/MIN.cs @@ -2,9 +2,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using SuperSocket; using SuperSocket.Command; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Tests.Command { diff --git a/test/SuperSocket.Tests.Command/SORT.cs b/test/SuperSocket.Tests.Command/SORT.cs index 15d33f5e2..84b62c5ea 100644 --- a/test/SuperSocket.Tests.Command/SORT.cs +++ b/test/SuperSocket.Tests.Command/SORT.cs @@ -2,9 +2,9 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using SuperSocket; using SuperSocket.Command; using SuperSocket.ProtoBase; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Tests.Command { diff --git a/test/SuperSocket.Tests/AspNetIntegrationTest.cs b/test/SuperSocket.Tests/AspNetIntegrationTest.cs index 7040278cc..ca0fd7a9f 100644 --- a/test/SuperSocket.Tests/AspNetIntegrationTest.cs +++ b/test/SuperSocket.Tests/AspNetIntegrationTest.cs @@ -12,6 +12,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using SuperSocket.Server; +using SuperSocket.Server.Host; using Microsoft.Extensions.Logging; namespace SuperSocket.Tests diff --git a/test/SuperSocket.Tests/AutofacTest.cs b/test/SuperSocket.Tests/AutofacTest.cs index d3470b1b2..0ee566950 100644 --- a/test/SuperSocket.Tests/AutofacTest.cs +++ b/test/SuperSocket.Tests/AutofacTest.cs @@ -18,6 +18,8 @@ using SuperSocket.Server; using System.Threading; using SuperSocket.Tests.Command; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Session; using Autofac.Extensions.DependencyInjection; using Autofac; using Microsoft.Extensions.Configuration; diff --git a/test/SuperSocket.Tests/BeginEndMarkProtocolTest.cs b/test/SuperSocket.Tests/BeginEndMarkProtocolTest.cs index 7f2210cec..53cb5e96a 100644 --- a/test/SuperSocket.Tests/BeginEndMarkProtocolTest.cs +++ b/test/SuperSocket.Tests/BeginEndMarkProtocolTest.cs @@ -8,7 +8,9 @@ using Microsoft.Extensions.Hosting; using SuperSocket; using SuperSocket.ProtoBase; -using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Host; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/ClientTest.cs b/test/SuperSocket.Tests/ClientTest.cs index 1749b5464..8a40ea356 100644 --- a/test/SuperSocket.Tests/ClientTest.cs +++ b/test/SuperSocket.Tests/ClientTest.cs @@ -22,8 +22,10 @@ using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; -using SuperSocket.Channel; +using SuperSocket.Server.Host; using SuperSocket.Tests.Command; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions.Session; using System.Threading; using Microsoft.Extensions.Logging.Abstractions; using SuperSocket.WebSocket; @@ -77,7 +79,7 @@ public async Task TestEcho(Type hostConfiguratorType, bool clientReadAsDemand) Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); - var options = new ChannelOptions + var options = new ConnectionOptions { Logger = NullLogger.Instance, ReadAsDemand = clientReadAsDemand @@ -135,7 +137,7 @@ public async Task TestBindLocalEndPoint(Type hostConfiguratorType) Decoder = new DefaultStringPackageDecoder() }; - var options = new ChannelOptions + var options = new ConnectionOptions { Logger = DefaultLoggerFactory.CreateLogger(nameof(TestBindLocalEndPoint)) }; @@ -184,7 +186,7 @@ public void TestCancellationTokenIsBeingUsedWhenConnecting() Decoder = new DefaultStringPackageDecoder() }; - var options = new ChannelOptions + var options = new ConnectionOptions { Logger = DefaultLoggerFactory.CreateLogger(nameof(TestBindLocalEndPoint)) }; @@ -230,7 +232,7 @@ public async Task TestCommandLine(Type hostConfiguratorType) Decoder = new DefaultStringPackageDecoder() }; - var options = new ChannelOptions + var options = new ConnectionOptions { Logger = DefaultLoggerFactory.CreateLogger(nameof(TestCommandLine)) }; @@ -289,7 +291,7 @@ public async Task TestDetachableChannel(Type hostConfiguratorType) await socket.ConnectAsync(hostConfigurator.GetServerEndPoint()); var stream = await hostConfigurator.GetClientStream(socket); - var channel = new StreamPipeChannel(stream, socket.RemoteEndPoint, socket.LocalEndPoint, new LinePipelineFilter(), new ChannelOptions + var channel = new StreamPipeConnection(stream, socket.RemoteEndPoint, socket.LocalEndPoint, new LinePipelineFilter(), new ConnectionOptions { Logger = DefaultLoggerFactory.CreateLogger(nameof(TestDetachableChannel)), ReadAsDemand = true diff --git a/test/SuperSocket.Tests/CommandTest.cs b/test/SuperSocket.Tests/CommandTest.cs index e5c17d923..0848b2b47 100644 --- a/test/SuperSocket.Tests/CommandTest.cs +++ b/test/SuperSocket.Tests/CommandTest.cs @@ -15,9 +15,14 @@ using Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; -using SuperSocket.Server; using System.Threading; using SuperSocket.Tests.Command; +using SuperSocket.Server; +using SuperSocket.Server.Connection; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Connections; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Tests { diff --git a/test/SuperSocket.Tests/Commands.cs b/test/SuperSocket.Tests/Commands.cs index 6182c9af5..632c70f98 100644 --- a/test/SuperSocket.Tests/Commands.cs +++ b/test/SuperSocket.Tests/Commands.cs @@ -4,6 +4,7 @@ using System.Text; using SuperSocket; using SuperSocket.Server; +using SuperSocket.Server.Abstractions.Session; using SuperSocket.Command; using SuperSocket.ProtoBase; using SuperSocket.Tests.Command; diff --git a/test/SuperSocket.Tests/FixedHeaderProtocolTest.cs b/test/SuperSocket.Tests/FixedHeaderProtocolTest.cs index 3cd198015..19da56e97 100644 --- a/test/SuperSocket.Tests/FixedHeaderProtocolTest.cs +++ b/test/SuperSocket.Tests/FixedHeaderProtocolTest.cs @@ -6,7 +6,8 @@ using Microsoft.Extensions.Hosting; using SuperSocket; using SuperSocket.ProtoBase; -using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/FixedSizeProtocolTest.cs b/test/SuperSocket.Tests/FixedSizeProtocolTest.cs index dfbe74b44..dd19ad12b 100644 --- a/test/SuperSocket.Tests/FixedSizeProtocolTest.cs +++ b/test/SuperSocket.Tests/FixedSizeProtocolTest.cs @@ -5,6 +5,8 @@ using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/GzipHostConfigurator.cs b/test/SuperSocket.Tests/GzipHostConfigurator.cs index 0c9f33f8f..197452f2d 100644 --- a/test/SuperSocket.Tests/GzipHostConfigurator.cs +++ b/test/SuperSocket.Tests/GzipHostConfigurator.cs @@ -10,10 +10,13 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; -using SuperSocket.GZip; using SuperSocket.ProtoBase; +using System.IO.Compression; +using SuperSocket.Server.Host; namespace SuperSocket.Tests { @@ -41,23 +44,30 @@ public override void Configure(ISuperSocketHostBuilder hostBuilder) } public override ValueTask GetClientStream(Socket socket) { - Stream stream = new GZipReadWriteStream(new NetworkStream(socket, false), false); + var networkStream = new NetworkStream(socket, false); + var stream = new ReadWriteDelegateStream( + networkStream, + new GZipStream(networkStream, CompressionMode.Decompress), + new GZipStream(networkStream, CompressionMode.Compress)); return new ValueTask(stream); } protected virtual SslProtocols GetServerEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } protected virtual SslProtocols GetClientEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } - public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) where TPackageInfo : class + public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) + where TPackageInfo : class { - return new GZipEasyClient(pipelineFilter, options); + var client = new EasyClient(pipelineFilter, options); + client.CompressionLevel = CompressionLevel.Optimal; + return client; } } diff --git a/test/SuperSocket.Tests/GzipSecureHostConfigurator.cs b/test/SuperSocket.Tests/GzipSecureHostConfigurator.cs index 9b3a8e352..297f0c224 100644 --- a/test/SuperSocket.Tests/GzipSecureHostConfigurator.cs +++ b/test/SuperSocket.Tests/GzipSecureHostConfigurator.cs @@ -10,10 +10,13 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; -using SuperSocket.GZip; using SuperSocket.ProtoBase; +using SuperSocket.Server.Host; +using System.IO.Compression; namespace SuperSocket.Tests { @@ -55,29 +58,36 @@ public override async ValueTask GetClientStream(Socket socket) options.EnabledSslProtocols = GetClientEnabledSslProtocols(); options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; await stream.AuthenticateAsClientAsync(options); - var zipStream = new GZipReadWriteStream(stream, true); + + var zipStream = new ReadWriteDelegateStream( + stream, + new GZipStream(stream, CompressionMode.Decompress), + new GZipStream(stream, CompressionMode.Compress)); + return zipStream; } protected virtual SslProtocols GetServerEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } protected virtual SslProtocols GetClientEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } - public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) where TPackageInfo : class + public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) + where TPackageInfo : class { - var client = new GZipEasyClient(pipelineFilter, options); + var client = new EasyClient(pipelineFilter, options); client.Security = new SecurityOptions { TargetHost = "supersocket", EnabledSslProtocols = GetClientEnabledSslProtocols(), RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true }; + client.CompressionLevel = CompressionLevel.Optimal; return client; } } diff --git a/test/SuperSocket.Tests/HttpPipelineFilterTest.cs b/test/SuperSocket.Tests/HttpPipelineFilterTest.cs index a05329d72..52e98f3d9 100644 --- a/test/SuperSocket.Tests/HttpPipelineFilterTest.cs +++ b/test/SuperSocket.Tests/HttpPipelineFilterTest.cs @@ -23,7 +23,8 @@ using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Host; namespace SuperSocket.Tests { @@ -48,14 +49,18 @@ public SecureEasyClient(IPipelineFilter pipelineFilter, ILogger protected override IConnector GetConnector() { var authOptions = new SslClientAuthenticationOptions(); - authOptions.EnabledSslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12; + authOptions.EnabledSslProtocols = SslProtocols.Tls12; authOptions.TargetHost = IPAddress.Loopback.ToString(); authOptions.RemoteCertificateValidationCallback += (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; }; - return new SocketConnector(new SslStreamConnector(authOptions)); + return BuildConnectors(new IConnector[] + { + new SocketConnector(), + new SslStreamConnector(authOptions) + }); } } diff --git a/test/SuperSocket.Tests/IHostConfigurator.cs b/test/SuperSocket.Tests/IHostConfigurator.cs index 02d8600bf..161c51bf3 100644 --- a/test/SuperSocket.Tests/IHostConfigurator.cs +++ b/test/SuperSocket.Tests/IHostConfigurator.cs @@ -5,7 +5,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Connections; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -29,7 +33,7 @@ public interface IHostConfigurator ListenOptions Listener { get; } - IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) + IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) where TPackageInfo : class; } } \ No newline at end of file diff --git a/test/SuperSocket.Tests/MainTest.cs b/test/SuperSocket.Tests/MainTest.cs index 6fed2c205..3fa044885 100644 --- a/test/SuperSocket.Tests/MainTest.cs +++ b/test/SuperSocket.Tests/MainTest.cs @@ -11,7 +11,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SuperSocket; +using SuperSocket.Connection; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using Microsoft.Extensions.Hosting.Internal; @@ -96,9 +100,9 @@ public void TestCustomConfigOptions() [Theory] [InlineData("Tls12", SslProtocols.Tls12, false)] [InlineData("Tls15", SslProtocols.None, true)] - [InlineData("Tls11, Tls12", SslProtocols.Tls11 | SslProtocols.Tls12, false)] - [InlineData("Tls11,Tls12", SslProtocols.Tls11 | SslProtocols.Tls12, false)] - [InlineData("Tls11|Tls12", SslProtocols.Tls11 | SslProtocols.Tls12, true)] + [InlineData("Tls13, Tls12", SslProtocols.Tls13 | SslProtocols.Tls12, false)] + [InlineData("Tls13,Tls12", SslProtocols.Tls13 | SslProtocols.Tls12, false)] + [InlineData("Tls13|Tls12", SslProtocols.Tls13 | SslProtocols.Tls12, true)] public async Task TestSecurityOptions(string security, SslProtocols protocols, bool expectException) { var hostConfigurator = new SecureHostConfigurator(); @@ -185,7 +189,7 @@ public async Task TestSessionHandlers(Type hostConfiguratorType) .UsePackageHandler(async (s, p) => { if (p.Text == "CLOSE") - await s.CloseAsync(Channel.CloseReason.LocalClosing); + await s.CloseAsync(CloseReason.LocalClosing); }).BuildAsServer()) { Assert.Equal("TestServer", server.Name); @@ -373,7 +377,7 @@ public async Task TestCloseAfterSend(Type hostConfiguratorType) .UsePackageHandler(async (IAppSession s, TextPackageInfo p) => { await s.SendAsync(Utf8Encoding.GetBytes("Hello World\r\n")); - await s.CloseAsync(Channel.CloseReason.LocalClosing); + await s.CloseAsync(CloseReason.LocalClosing); }).BuildAsServer() as IServer) { Assert.True(await server.StartAsync()); diff --git a/test/SuperSocket.Tests/ObjectPipeTest.cs b/test/SuperSocket.Tests/ObjectPipeTest.cs index 977ce8e37..0e7ad1e89 100644 --- a/test/SuperSocket.Tests/ObjectPipeTest.cs +++ b/test/SuperSocket.Tests/ObjectPipeTest.cs @@ -5,7 +5,7 @@ using Xunit; using Xunit.Abstractions; using System.Threading; -using SuperSocket.Channel; +using SuperSocket.Connection; namespace SuperSocket.Tests { diff --git a/test/SuperSocket.Tests/PackageHandlingContextAccessorTest.cs b/test/SuperSocket.Tests/PackageHandlingContextAccessorTest.cs index 6e0f5af28..69d6fe2c1 100644 --- a/test/SuperSocket.Tests/PackageHandlingContextAccessorTest.cs +++ b/test/SuperSocket.Tests/PackageHandlingContextAccessorTest.cs @@ -2,6 +2,9 @@ using SuperSocket.Command; using SuperSocket.ProtoBase; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Host; +using SuperSocket.Server.Abstractions.Session; using System; using System.Collections.Generic; using System.IO; diff --git a/test/SuperSocket.Tests/ProtocolTestBase.cs b/test/SuperSocket.Tests/ProtocolTestBase.cs index ccb0abb5e..769865583 100644 --- a/test/SuperSocket.Tests/ProtocolTestBase.cs +++ b/test/SuperSocket.Tests/ProtocolTestBase.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using SuperSocket; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/RegularHostConfigurator.cs b/test/SuperSocket.Tests/RegularHostConfigurator.cs index 9b0657a51..cc9101cb7 100644 --- a/test/SuperSocket.Tests/RegularHostConfigurator.cs +++ b/test/SuperSocket.Tests/RegularHostConfigurator.cs @@ -8,7 +8,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -21,7 +23,8 @@ public RegularHostConfigurator() WebSocketSchema = "ws"; } - public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) where TPackageInfo : class + public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) + where TPackageInfo : class { return new EasyClient(pipelineFilter, options); } diff --git a/test/SuperSocket.Tests/SecureHostConfigurator.cs b/test/SuperSocket.Tests/SecureHostConfigurator.cs index 93d49583f..8fd1195dd 100644 --- a/test/SuperSocket.Tests/SecureHostConfigurator.cs +++ b/test/SuperSocket.Tests/SecureHostConfigurator.cs @@ -10,7 +10,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -58,15 +60,16 @@ public override async ValueTask GetClientStream(Socket socket) protected virtual SslProtocols GetServerEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } protected virtual SslProtocols GetClientEnabledSslProtocols() { - return SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11; + return SslProtocols.Tls13 | SslProtocols.Tls12; } - public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) where TPackageInfo : class + public override IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) + where TPackageInfo : class { var client = new EasyClient(pipelineFilter, options); client.Security = new SecurityOptions diff --git a/test/SuperSocket.Tests/ServerOptionsTest.cs b/test/SuperSocket.Tests/ServerOptionsTest.cs index 1fc66c750..ab1801a5a 100644 --- a/test/SuperSocket.Tests/ServerOptionsTest.cs +++ b/test/SuperSocket.Tests/ServerOptionsTest.cs @@ -11,6 +11,8 @@ using SuperSocket; using SuperSocket.Command; using SuperSocket.ProtoBase; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Host; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Xunit; diff --git a/test/SuperSocket.Tests/SessionContainerTest.cs b/test/SuperSocket.Tests/SessionContainerTest.cs index f8484875e..c59676a43 100644 --- a/test/SuperSocket.Tests/SessionContainerTest.cs +++ b/test/SuperSocket.Tests/SessionContainerTest.cs @@ -16,7 +16,10 @@ using Xunit; using Xunit.Abstractions; using System.Threading; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Host; namespace SuperSocket.Tests { diff --git a/test/SuperSocket.Tests/SessionTest.cs b/test/SuperSocket.Tests/SessionTest.cs index 4f0527bf1..7a72659a8 100644 --- a/test/SuperSocket.Tests/SessionTest.cs +++ b/test/SuperSocket.Tests/SessionTest.cs @@ -12,7 +12,10 @@ using SuperSocket; using System.Linq; using System.Reflection; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Session; +using SuperSocket.Server.Host; using Microsoft.Extensions.Configuration; using System.Collections.Generic; @@ -89,7 +92,7 @@ public async Task TestSessionEvents() session.Reset(); - Assert.Null(session.Channel); + Assert.Null(session.Connection); Assert.Null(session.DataContext); Assert.Equal(SessionState.None, session.State); Assert.Null(session[itemKey]); diff --git a/test/SuperSocket.Tests/SuperSocket.Tests.csproj b/test/SuperSocket.Tests/SuperSocket.Tests.csproj index a1474119c..78a4e7559 100755 --- a/test/SuperSocket.Tests/SuperSocket.Tests.csproj +++ b/test/SuperSocket.Tests/SuperSocket.Tests.csproj @@ -7,13 +7,11 @@ - - diff --git a/test/SuperSocket.Tests/SwitchProtocolTest.cs b/test/SuperSocket.Tests/SwitchProtocolTest.cs index 9ec2a9a46..261df80e2 100644 --- a/test/SuperSocket.Tests/SwitchProtocolTest.cs +++ b/test/SuperSocket.Tests/SwitchProtocolTest.cs @@ -6,6 +6,8 @@ using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Host; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/TcpHostConfigurator.cs b/test/SuperSocket.Tests/TcpHostConfigurator.cs index 59ca79a9b..f7a6d4121 100644 --- a/test/SuperSocket.Tests/TcpHostConfigurator.cs +++ b/test/SuperSocket.Tests/TcpHostConfigurator.cs @@ -8,7 +8,9 @@ using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -48,7 +50,7 @@ public TextReader GetStreamReader(Stream stream, Encoding encoding) return new StreamReader(stream, encoding, true); } - public abstract IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) + public abstract IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) where TPackageInfo : class; public abstract ValueTask GetClientStream(Socket socket); diff --git a/test/SuperSocket.Tests/TerminatorProtocolTest.cs b/test/SuperSocket.Tests/TerminatorProtocolTest.cs index 76ae7a481..c85cf1440 100644 --- a/test/SuperSocket.Tests/TerminatorProtocolTest.cs +++ b/test/SuperSocket.Tests/TerminatorProtocolTest.cs @@ -4,6 +4,8 @@ using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Host; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/TestClassBase.cs b/test/SuperSocket.Tests/TestClassBase.cs index 5682b2f19..eaf9c24e4 100644 --- a/test/SuperSocket.Tests/TestClassBase.cs +++ b/test/SuperSocket.Tests/TestClassBase.cs @@ -11,6 +11,8 @@ using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions.Host; using Xunit; using Xunit.Abstractions; diff --git a/test/SuperSocket.Tests/UdpChannelStream.cs b/test/SuperSocket.Tests/UdpChannelStream.cs index a4dc89dc0..9aa972312 100644 --- a/test/SuperSocket.Tests/UdpChannelStream.cs +++ b/test/SuperSocket.Tests/UdpChannelStream.cs @@ -1,14 +1,14 @@ using System; using System.IO; using System.Net.Sockets; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Tests { public class UdpChannelStream : Stream { - public UdpPipeChannel Channel { get; } + public UdpPipeConnection Connection { get; } public override bool CanRead => true; @@ -22,9 +22,9 @@ public class UdpChannelStream : Stream public Socket Socket { get; } - public UdpChannelStream(UdpPipeChannel channel, Socket socket) + public UdpChannelStream(UdpPipeConnection connection, Socket socket) { - Channel = channel; + Connection = connection; Socket = socket; } @@ -50,7 +50,7 @@ public override int Read(byte[] buffer, int offset, int count) public override void Write(byte[] buffer, int offset, int count) { - Channel + Connection .SendAsync((new ArraySegment(buffer, offset, count)).AsMemory()) .GetAwaiter() .GetResult(); diff --git a/test/SuperSocket.Tests/UdpHostConfigurator.cs b/test/SuperSocket.Tests/UdpHostConfigurator.cs index 2c247ed8f..b4efd46dc 100644 --- a/test/SuperSocket.Tests/UdpHostConfigurator.cs +++ b/test/SuperSocket.Tests/UdpHostConfigurator.cs @@ -7,7 +7,9 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using SuperSocket.Channel; +using SuperSocket.Connection; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Client; using SuperSocket.ProtoBase; @@ -40,7 +42,8 @@ public void Configure(ISuperSocketHostBuilder hostBuilder) ); } - public IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ChannelOptions options) where TPackageInfo : class + public IEasyClient ConfigureEasyClient(IPipelineFilter pipelineFilter, ConnectionOptions options) + where TPackageInfo : class { return new EasyClient(pipelineFilter, options); } @@ -68,7 +71,7 @@ public Socket CreateClient() throw new Exception("Cannot find an available port for udp client binding."); } - private async Task UdpReceive(Socket socket, IVirtualChannel channel) + private async Task UdpReceive(Socket socket, IVirtualConnection connection) { var remoteEndPoint = new IPEndPoint(IPAddress.Any, 4040); @@ -82,7 +85,7 @@ private async Task UdpReceive(Socket socket, IVirtualChannel channel) .ReceiveFromAsync(new ArraySegment(buffer, 0, buffer.Length), SocketFlags.None, remoteEndPoint) .ConfigureAwait(false); - await channel.WritePipeDataAsync((new ArraySegment(buffer, 0, result.ReceivedBytes)).AsMemory(), CancellationToken.None); + await connection.WritePipeDataAsync((new ArraySegment(buffer, 0, result.ReceivedBytes)).AsMemory(), CancellationToken.None); } catch (NullReferenceException) { @@ -101,11 +104,11 @@ private async Task UdpReceive(Socket socket, IVirtualChannel channel) public ValueTask GetClientStream(Socket socket) { - var channel = new UdpPipeChannel(socket, new TerminatorPipelineFilter(new[] { (byte)'\r', (byte)'\n'}) + var channel = new UdpPipeConnection(socket, new TerminatorPipelineFilter(new[] { (byte)'\r', (byte)'\n'}) { Decoder = new UdpPackageDecoder() }, - new ChannelOptions(), new IPEndPoint(IPAddress.Loopback, Listener.GetListenEndPoint().Port)); + new ConnectionOptions(), new IPEndPoint(IPAddress.Loopback, Listener.ToEndPoint().Port)); channel.Start(); @@ -116,8 +119,8 @@ public ValueTask GetClientStream(Socket socket) public TextReader GetStreamReader(Stream stream, Encoding encoding) { - var channel = (stream as UdpChannelStream).Channel; - return new UdpTextReader(channel); + var connection = (stream as UdpChannelStream).Connection; + return new UdpTextReader(connection); } class UdpPackageDecoder : IPackageDecoder diff --git a/test/SuperSocket.Tests/UdpTextReader.cs b/test/SuperSocket.Tests/UdpTextReader.cs index 78a6e9332..f37c1d7a6 100644 --- a/test/SuperSocket.Tests/UdpTextReader.cs +++ b/test/SuperSocket.Tests/UdpTextReader.cs @@ -2,21 +2,21 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; -using SuperSocket.Channel; +using SuperSocket.Connection; using SuperSocket.ProtoBase; namespace SuperSocket.Tests { public class UdpTextReader : TextReader { - public UdpPipeChannel Channel { get; } + public UdpPipeConnection Connection { get; } private IAsyncEnumerator _packageEnumerator; - public UdpTextReader(UdpPipeChannel channel) + public UdpTextReader(UdpPipeConnection connection) { - Channel = channel; - _packageEnumerator = channel.RunAsync().GetAsyncEnumerator(); + Connection = connection; + _packageEnumerator = connection.RunAsync().GetAsyncEnumerator(); } public override string ReadLine() diff --git a/test/SuperSocket.Tests/WebSocket/WebSocketBasicTest.cs b/test/SuperSocket.Tests/WebSocket/WebSocketBasicTest.cs index cf4af5b19..4738b91cc 100644 --- a/test/SuperSocket.Tests/WebSocket/WebSocketBasicTest.cs +++ b/test/SuperSocket.Tests/WebSocket/WebSocketBasicTest.cs @@ -20,9 +20,13 @@ using SuperSocket.ProtoBase; using SuperSocket.WebSocket; using SuperSocket.Server; +using SuperSocket.Server.Host; +using SuperSocket.Server.Abstractions; +using SuperSocket.Server.Abstractions.Host; using SuperSocket.Tests.Command; using Xunit; using Xunit.Abstractions; +using SuperSocket.Server.Abstractions.Session; namespace SuperSocket.Tests.WebSocket diff --git a/test/SuperSocket.Tests/WebSocket/WebSocketServerTestBase.cs b/test/SuperSocket.Tests/WebSocket/WebSocketServerTestBase.cs index 3e2af97de..06dfbee68 100644 --- a/test/SuperSocket.Tests/WebSocket/WebSocketServerTestBase.cs +++ b/test/SuperSocket.Tests/WebSocket/WebSocketServerTestBase.cs @@ -11,6 +11,7 @@ using SuperSocket; using SuperSocket.WebSocket.Server; using SuperSocket.WebSocket; +using SuperSocket.Server.Abstractions.Host; namespace SuperSocket.Tests.WebSocket {