sample:discard,factorial,securechat,telnet (#142)

Squashed commit:

[7fbc42e] comment about BigInteger.ToByteArray()

[3be0644] delete ChannelInboundHander and ChannelInboudnHandlerAdpter

[b07f8d9] fix Microsoft.Practices compile error, use echo proj's version

[c19a551] sample:discard,factorial,securechat,telnet
This commit is contained in:
egmkang wang 2016-07-26 01:17:54 +08:00 коммит произвёл Max Gortman
Родитель 97d90cf026
Коммит a9850b4775
64 изменённых файлов: 2713 добавлений и 2 удалений

Просмотреть файл

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
VisualStudioVersion = 14.0.25420.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetty.Common", "src\DotNetty.Common\DotNetty.Common.csproj", "{DE58FE41-5E99-44E5-86BC-FC9ED8761DAF}"
EndProject
@ -59,6 +59,32 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetty.Transport.Tests.Pe
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DotNetty.Handlers.Tests", "test\DotNetty.Handlers.Tests\DotNetty.Handlers.Tests.csproj", "{0F5AC479-520B-476F-8E2B-1849F5B63A91}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Factorial", "Factorial", "{AD047ADA-2282-4626-BE51-5B978BC00B03}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Discard", "Discard", "{9C0335DC-7DD0-4D0B-AB26-91F9D1EF9BB4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Factorial", "examples\Factorial\Factorial.csproj", "{C7559BFC-023F-445E-BAB8-E2B5E199B774}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Discard.Client", "examples\Discard.Client\Discard.Client.csproj", "{124620F1-A3B6-4B8D-9954-61BF2021DF39}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Discard.Server", "examples\Discard.Server\Discard.Server.csproj", "{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Factorial.Server", "examples\Factorial.Server\Factorial.Server.csproj", "{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Factorial.Client", "examples\Factorial.Client\Factorial.Client.csproj", "{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Telnet", "Telnet", "{74506CCF-00FF-40CD-B892-2A6A3FF5CEA6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telnet.Client", "examples\Telnet.Client\Telnet.Client.csproj", "{ABABFE48-551E-4C4B-8640-B334329D5C5D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telnet.Server", "examples\Telnet.Server\Telnet.Server.csproj", "{5543847A-8509-4646-8472-1E4450025FDF}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SecureChat", "SecureChat", "{C98D8C38-759D-492E-B5E5-B4BBA65A6AC5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecureChat.Client", "examples\SecureChat.Client\SecureChat.Client.csproj", "{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SecureChat.Server", "examples\SecureChat.Server\SecureChat.Server.csproj", "{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -166,6 +192,60 @@ Global
{0F5AC479-520B-476F-8E2B-1849F5B63A91}.Release|Any CPU.Build.0 = Release|Any CPU
{0F5AC479-520B-476F-8E2B-1849F5B63A91}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{0F5AC479-520B-476F-8E2B-1849F5B63A91}.Signed|Any CPU.Build.0 = Release|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Release|Any CPU.Build.0 = Release|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{C7559BFC-023F-445E-BAB8-E2B5E199B774}.Signed|Any CPU.Build.0 = Release|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Debug|Any CPU.Build.0 = Debug|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Release|Any CPU.ActiveCfg = Release|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Release|Any CPU.Build.0 = Release|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{124620F1-A3B6-4B8D-9954-61BF2021DF39}.Signed|Any CPU.Build.0 = Release|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Release|Any CPU.Build.0 = Release|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}.Signed|Any CPU.Build.0 = Release|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Release|Any CPU.Build.0 = Release|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}.Signed|Any CPU.Build.0 = Release|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Release|Any CPU.Build.0 = Release|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}.Signed|Any CPU.Build.0 = Release|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Release|Any CPU.Build.0 = Release|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{ABABFE48-551E-4C4B-8640-B334329D5C5D}.Signed|Any CPU.Build.0 = Release|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Release|Any CPU.Build.0 = Release|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{5543847A-8509-4646-8472-1E4450025FDF}.Signed|Any CPU.Build.0 = Release|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Release|Any CPU.Build.0 = Release|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}.Signed|Any CPU.Build.0 = Release|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Release|Any CPU.Build.0 = Release|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Signed|Any CPU.ActiveCfg = Release|Any CPU
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}.Signed|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -190,5 +270,18 @@ Global
{EDF30087-8B53-4432-84B8-D21BD9F49E95} = {6A0821D4-8A5D-42AD-8E3F-F519100F4AD8}
{F2C39894-476D-441D-878F-23A03B848E06} = {6A0821D4-8A5D-42AD-8E3F-F519100F4AD8}
{0F5AC479-520B-476F-8E2B-1849F5B63A91} = {6A0821D4-8A5D-42AD-8E3F-F519100F4AD8}
{AD047ADA-2282-4626-BE51-5B978BC00B03} = {2B766264-D269-415C-8F2A-5AFC44409C01}
{9C0335DC-7DD0-4D0B-AB26-91F9D1EF9BB4} = {2B766264-D269-415C-8F2A-5AFC44409C01}
{C7559BFC-023F-445E-BAB8-E2B5E199B774} = {AD047ADA-2282-4626-BE51-5B978BC00B03}
{124620F1-A3B6-4B8D-9954-61BF2021DF39} = {9C0335DC-7DD0-4D0B-AB26-91F9D1EF9BB4}
{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4} = {9C0335DC-7DD0-4D0B-AB26-91F9D1EF9BB4}
{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B} = {AD047ADA-2282-4626-BE51-5B978BC00B03}
{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2} = {AD047ADA-2282-4626-BE51-5B978BC00B03}
{74506CCF-00FF-40CD-B892-2A6A3FF5CEA6} = {2B766264-D269-415C-8F2A-5AFC44409C01}
{ABABFE48-551E-4C4B-8640-B334329D5C5D} = {74506CCF-00FF-40CD-B892-2A6A3FF5CEA6}
{5543847A-8509-4646-8472-1E4450025FDF} = {74506CCF-00FF-40CD-B892-2A6A3FF5CEA6}
{C98D8C38-759D-492E-B5E5-B4BBA65A6AC5} = {2B766264-D269-415C-8F2A-5AFC44409C01}
{B6C42665-2A5B-4BFD-B5B9-965C31A383D3} = {C98D8C38-759D-492E-B5E5-B4BBA65A6AC5}
{DDA47BCE-752F-4DEE-BB75-28E7D6921E79} = {C98D8C38-759D-492E-B5E5-B4BBA65A6AC5}
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="host" value="127.0.0.1" />
<add key="port" value="8007" />
<add key="size" value="256"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{124620F1-A3B6-4B8D-9954-61BF2021DF39}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Discard.Client</RootNamespace>
<AssemblyName>Discard.Client</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="DiscardSettings.cs" />
<Compile Include="DiscardClientHandler.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config">
<SubType>Designer</SubType>
</None>
<None Include="packages.config">
<SubType>
</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,53 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Client
{
using System;
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
public class DiscardClientHandler : SimpleChannelInboundHandler<object>
{
private IChannelHandlerContext ctx;
private byte[] array;
public override void ChannelActive(IChannelHandlerContext ctx)
{
this.array = new byte[DiscardClientSettings.Size];
this.ctx = ctx;
// Send the initial messages.
this.GenerateTraffic();
}
protected override void ChannelRead0(IChannelHandlerContext context, object message)
{
// Server is supposed to send nothing, but if it sends something, discard it.
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e)
{
Console.WriteLine("{0}", e.ToString());
this.ctx.CloseAsync();
}
private async void GenerateTraffic()
{
try
{
IByteBuffer buffer = Unpooled.WrappedBuffer(this.array);
// Flush the outbound buffer to the socket.
// Once flushed, generate the same amount of traffic again.
await this.ctx.WriteAndFlushAsync(buffer);
GenerateTraffic();
}
catch
{
await this.ctx.CloseAsync();
}
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Client
{
using System.Configuration;
using System.Net;
public static class DiscardClientSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static IPAddress Host => IPAddress.Parse(ConfigurationManager.AppSettings["host"]);
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
public static int Size => int.Parse(ConfigurationManager.AppSettings["size"]);
}
}

Просмотреть файл

@ -0,0 +1,71 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Client
{
using System;
using System.Diagnostics.Tracing;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunClientAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
var group = new MultithreadEventLoopGroup();
X509Certificate2 cert = null;
string targetHost = null;
if (DiscardClientSettings.IsSsl)
{
cert = new X509Certificate2("dotnetty.com.pfx", "password");
targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
}
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (cert != null)
{
pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
}
pipeline.AddLast(new DiscardClientHandler());
}));
IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(DiscardClientSettings.Host, DiscardClientSettings.Port));
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
group.ShutdownGracefullyAsync().Wait(1000);
eventListener.Dispose();
}
}
static void Main() => RunClientAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Discard.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Discard.Client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("124620f1-a3b6-4b8d-9954-61bf2021df39")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="port" value="8007" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,96 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{821D5A3F-F4CD-4579-A0A0-95F6770F1DC4}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Discard.Server</RootNamespace>
<AssemblyName>Discard.Server</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="DiscardServerHandler.cs" />
<Compile Include="DiscardSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config">
<SubType>
</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Server
{
using System;
using DotNetty.Buffers;
using DotNetty.Transport.Channels;
public class DiscardServerHandler : SimpleChannelInboundHandler<object>
{
protected override void ChannelRead0(IChannelHandlerContext context, object message)
{
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e)
{
Console.WriteLine("{0}", e.ToString());
ctx.CloseAsync();
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Server
{
using System.Configuration;
public static class DiscardSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
}
}

Просмотреть файл

@ -0,0 +1,68 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Discard.Server
{
using System;
using System.Diagnostics.Tracing;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunServerAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);
var bossGroup = new MultithreadEventLoopGroup(1);
var workerGroup = new MultithreadEventLoopGroup();
X509Certificate2 tlsCertificate = null;
if (DiscardSettings.IsSsl)
{
tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
}
try
{
var bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler(LogLevel.INFO))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
pipeline.AddLast(new DiscardServerHandler());
}));
IChannel bootstrapChannel = await bootstrap.BindAsync(DiscardSettings.Port);
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
eventListener.Dispose();
}
}
static void Main() => RunServerAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Discard.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Discard.Server")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("821d5a3f-f4cd-4579-a0a0-95f6770f1dc4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="host" value="127.0.0.1" />
<add key="port" value="8007" />
<add key="count" value="100"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E7B7F314-6E72-4CE1-B69C-F5732DCF07F2}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Factorial.Client</RootNamespace>
<AssemblyName>Factorial.Client</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
</ItemGroup>
<ItemGroup>
<Compile Include="FactorialClientHandler.cs" />
<Compile Include="FactorialSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
<ProjectReference Include="..\Factorial\Factorial.csproj">
<Project>{c7559bfc-023f-445e-bab8-e2b5e199b774}</Project>
<Name>Factorial</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,77 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Client
{
using System.Numerics;
using System;
using System.Collections.Concurrent;
using DotNetty.Transport.Channels;
public class FactorialClientHandler : SimpleChannelInboundHandler<BigInteger>
{
private IChannelHandlerContext ctx;
private int receivedMessages;
private int next = 1;
readonly ConcurrentQueue<BigInteger> answer = new ConcurrentQueue<BigInteger>();
public BigInteger GetFactorial()
{
bool interrupted = false;
BigInteger result = new BigInteger(1);
try
{
for (;;)
{
try
{
if (this.answer.TryDequeue(out result))
return result;
}
catch
{
interrupted = true;
}
}
}
finally
{
if (interrupted)
{
System.Threading.Thread.CurrentThread.Interrupt();
}
}
}
public FactorialClientHandler()
{
}
public override void ChannelActive(IChannelHandlerContext ctx)
{
this.ctx = ctx;
this.SendNumbers();
}
protected override void ChannelRead0(IChannelHandlerContext ctx, BigInteger msg)
{
this.receivedMessages++;
this.answer.Enqueue(msg);
if (this.receivedMessages == FactorialClientSettings.Count)
{
Console.WriteLine("Factorial of {0} is: {1}", FactorialClientSettings.Count, msg);
ctx.CloseAsync();
}
}
private void SendNumbers()
{
for (int i = 0; i < 4096 && next <= FactorialClientSettings.Count; i++)
{
ctx.WriteAsync(new BigInteger(next));
next++;
}
ctx.Flush();
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Client
{
using System.Configuration;
using System.Net;
public static class FactorialClientSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static IPAddress Host => IPAddress.Parse(ConfigurationManager.AppSettings["host"]);
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
public static int Count => int.Parse(ConfigurationManager.AppSettings["count"]);
}
}

Просмотреть файл

@ -0,0 +1,72 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Client
{
using System;
using System.Diagnostics.Tracing;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunClientAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
var group = new MultithreadEventLoopGroup();
X509Certificate2 cert = null;
string targetHost = null;
if (FactorialClientSettings.IsSsl)
{
cert = new X509Certificate2("dotnetty.com.pfx", "password");
targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
}
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (cert != null)
{
pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
}
pipeline.AddLast(new Factorial.BigIntegerDecoder());
pipeline.AddLast(new Factorial.NumberEncoder());
pipeline.AddLast(new FactorialClientHandler());
}));
IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(FactorialClientSettings.Host, FactorialClientSettings.Port));
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
group.ShutdownGracefullyAsync().Wait(1000);
eventListener.Dispose();
}
}
static void Main() => RunClientAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Factorial.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Factorial.Client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e7b7f314-6e72-4ce1-b69c-f5732dcf07f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="port" value="8007" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,101 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CAA57BA8-D7F2-467E-8F6F-5BA5B55A2F0B}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Factorial.Server</RootNamespace>
<AssemblyName>Factorial.Server</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
</ItemGroup>
<ItemGroup>
<Compile Include="FactorialServerHandler.cs" />
<Compile Include="FactorialSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config">
<SubType>
</SubType>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
<ProjectReference Include="..\Factorial\Factorial.csproj">
<Project>{c7559bfc-023f-445e-bab8-e2b5e199b774}</Project>
<Name>Factorial</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,32 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Server
{
using System;
using System.Numerics;
using DotNetty.Transport.Channels;
public class FactorialServerHandler : SimpleChannelInboundHandler<BigInteger>
{
private BigInteger lastMultiplier = new BigInteger(1);
private BigInteger factorial = new BigInteger(1);
protected override void ChannelRead0(IChannelHandlerContext ctx, BigInteger msg)
{
this.lastMultiplier = msg;
this.factorial *= msg;
ctx.WriteAndFlushAsync(factorial);
}
public override void ChannelInactive(IChannelHandlerContext ctx)
{
System.Console.WriteLine("Factorial of {0} is: {1}", lastMultiplier, factorial);
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e)
{
ctx.CloseAsync();
}
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Server
{
using System.Configuration;
public static class FactorialSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
}
}

Просмотреть файл

@ -0,0 +1,66 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial.Server
{
using System;
using System.Diagnostics.Tracing;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunServerAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);
var bossGroup = new MultithreadEventLoopGroup(1);
var workerGroup = new MultithreadEventLoopGroup();
X509Certificate2 tlsCertificate = null;
if (FactorialSettings.IsSsl)
{
tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
}
try
{
var bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler(LogLevel.INFO))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
pipeline.AddLast(new Factorial.NumberEncoder(), new Factorial.BigIntegerDecoder(), new FactorialServerHandler());
}));
IChannel bootstrapChannel = await bootstrap.BindAsync(FactorialSettings.Port);
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
eventListener.Dispose();
}
}
static void Main() => RunServerAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Factorial.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Factorial.Server")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("caa57ba8-d7f2-467e-8f6f-5ba5b55a2f0b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,40 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial
{
using System;
using System.Collections.Generic;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
public class BigIntegerDecoder : ByteToMessageDecoder
{
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
if (input.ReadableBytes < 5)
{
return;
}
input.MarkReaderIndex();
int magicNumber = input.ReadByte();
if (magicNumber != 'F')
{
input.ResetReaderIndex();
throw new Exception("Invalid magic number: " + magicNumber);
}
int dataLength = input.ReadInt();
if (input.ReadableBytes < dataLength)
{
input.ResetReaderIndex();
return;
}
byte[] decoded = new byte[dataLength];
input.ReadBytes(decoded);
output.Add(new System.Numerics.BigInteger(decoded));
}
}
}

Просмотреть файл

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C7559BFC-023F-445E-BAB8-E2B5E199B774}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Factorial</RootNamespace>
<AssemblyName>Factorial</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Numerics" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BigIntegerDecoder.cs" />
<Compile Include="NumberEncoder.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,28 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Factorial
{
using System.Collections.Generic;
using System.Numerics;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
public class NumberEncoder : MessageToMessageEncoder<BigInteger>
{
protected override void Encode(IChannelHandlerContext context, BigInteger message, List<object> output)
{
IByteBuffer buffer = context.Allocator.Buffer();
//https://msdn.microsoft.com/en-us/library/system.numerics.biginteger.tobytearray(v=vs.110).aspx
//BigInteger.ToByteArray() return a Little-Endian bytes
//IByteBuffer is Big-Endian by default
byte[] data = message.ToByteArray();
buffer.WriteByte((byte)'F');
buffer.WriteInt(data.Length);
buffer.WriteBytes(data);
output.Add(buffer);
}
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Factorial")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Factorial")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c7559bfc-023f-445e-bab8-e2b5e199b774")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="host" value="127.0.0.1" />
<add key="port" value="8008" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,87 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Client
{
using System;
using System.Diagnostics.Tracing;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunClientAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
var group = new MultithreadEventLoopGroup();
X509Certificate2 cert = null;
string targetHost = null;
if (SecureChatClientSettings.IsSsl)
{
cert = new X509Certificate2("dotnetty.com.pfx", "password");
targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
}
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (cert != null)
{
pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
}
pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
pipeline.AddLast(new StringEncoder(), new StringDecoder(), new SecureChatClientHandler());
}));
IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(SecureChatClientSettings.Host, SecureChatClientSettings.Port));
for (;;)
{
string line = Console.ReadLine();
if (String.IsNullOrEmpty(line))
{
continue;
}
try { await bootstrapChannel.WriteAndFlushAsync(line + "\r\n"); }
catch { }
if (line.ToLower() == "bye")
{
await bootstrapChannel.CloseAsync();
break;
}
}
await bootstrapChannel.CloseAsync();
}
finally
{
group.ShutdownGracefullyAsync().Wait(1000);
eventListener.Dispose();
}
}
static void Main() => RunClientAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SecureChat.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SecureChat.Client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b6c42665-2a5b-4bfd-b5b9-965c31a383d3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B6C42665-2A5B-4BFD-B5B9-965C31A383D3}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SecureChat.Client</RootNamespace>
<AssemblyName>SecureChat.Client</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SecureChatClientHandler.cs" />
<Compile Include="SecureChatClientSettings.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Client
{
using System;
using DotNetty.Transport.Channels;
public class SecureChatClientHandler : SimpleChannelInboundHandler<string>
{
protected override void ChannelRead0(IChannelHandlerContext contex, string msg)
{
Console.WriteLine(msg);
}
public override void ExceptionCaught(IChannelHandlerContext contex, Exception e)
{
Console.WriteLine(DateTime.Now.Millisecond);
Console.WriteLine("{0}", e.StackTrace);
contex.CloseAsync();
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Client
{
using System.Configuration;
using System.Net;
public static class SecureChatClientSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static IPAddress Host => IPAddress.Parse(ConfigurationManager.AppSettings["host"]);
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
public static int Count => int.Parse(ConfigurationManager.AppSettings["count"]);
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="port" value="8008" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,74 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Server
{
using System;
using System.Diagnostics.Tracing;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunServerAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);
var bossGroup = new MultithreadEventLoopGroup(1);
var workerGroup = new MultithreadEventLoopGroup();
var STRING_ENCODER = new StringEncoder();
var STRING_DECODER = new StringDecoder();
var SERVER_HANDLER = new SecureChatServerHandler();
X509Certificate2 tlsCertificate = null;
if (SecureChatSettings.IsSsl)
{
tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
}
try
{
var bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler(LogLevel.INFO))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
}));
IChannel bootstrapChannel = await bootstrap.BindAsync(SecureChatSettings.Port);
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
eventListener.Dispose();
}
}
static void Main() => RunServerAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SecureChat.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SecureChat.Server")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dda47bce-752f-4dee-bb75-28e7d6921e79")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{DDA47BCE-752F-4DEE-BB75-28E7D6921E79}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SecureChat.Server</RootNamespace>
<AssemblyName>SecureChat.Server</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SecureChatServerHandler.cs" />
<Compile Include="SecureChatSettings.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,70 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Server
{
using System;
using System.Net;
using DotNetty.Transport.Channels.Groups;
using DotNetty.Transport.Channels;
public class SecureChatServerHandler : SimpleChannelInboundHandler<String>
{
static IChannelGroup group = null;
public override void ChannelActive(IChannelHandlerContext contex)
{
lock (this)
{
if (group == null)
{
group = new DefaultChannelGroup(contex.Executor);
}
}
contex.WriteAndFlushAsync(String.Format("Welcome to {0} secure chat server!\n", Dns.GetHostName()));
group.Add(contex.Channel);
}
class EveryOneBut : IChannelMatcher
{
IChannelId id;
public EveryOneBut(IChannelId id)
{
this.id = id;
}
public bool Matches(IChannel channel)
{
return channel.Id != this.id;
}
}
protected override void ChannelRead0(IChannelHandlerContext contex, string msg)
{
//send message to all but this one
string broadcast = String.Format("[{0}] {1}\n", contex.Channel.RemoteAddress, msg);
string response = String.Format("[you] {0}\n", msg);
group.WriteAndFlushAsync(broadcast, new EveryOneBut(contex.Channel.Id));
contex.WriteAndFlushAsync(response);
if ("bye" == msg.ToLower())
{
contex.CloseAsync();
}
}
public override void ChannelReadComplete(IChannelHandlerContext contex)
{
contex.Flush();
}
public override void ExceptionCaught(IChannelHandlerContext contex, Exception e)
{
Console.WriteLine("{0}", e.StackTrace);
contex.CloseAsync();
}
public override bool IsSharable => true;
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SecureChat.Server
{
using System.Configuration;
public static class SecureChatSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net45" />
</packages>

Просмотреть файл

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="host" value="127.0.0.1" />
<add key="port" value="8007" />
<add key="count" value="100"/>
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,87 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Client
{
using System;
using System.Diagnostics.Tracing;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunClientAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.Verbose);
var group = new MultithreadEventLoopGroup();
X509Certificate2 cert = null;
string targetHost = null;
if (TelnetClientSettings.IsSsl)
{
cert = new X509Certificate2("dotnetty.com.pfx", "password");
targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
}
try
{
var bootstrap = new Bootstrap();
bootstrap
.Group(group)
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (cert != null)
{
pipeline.AddLast(new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)));
}
pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
pipeline.AddLast(new StringEncoder(), new StringDecoder(), new TelnetClientHandler());
}));
IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(TelnetClientSettings.Host, TelnetClientSettings.Port));
for (;;)
{
string line = Console.ReadLine();
if (String.IsNullOrEmpty(line))
{
continue;
}
try { await bootstrapChannel.WriteAndFlushAsync(line + "\r\n"); }
catch { }
if (line.ToLower() == "bye")
{
await bootstrapChannel.CloseAsync();
break;
}
}
await bootstrapChannel.CloseAsync();
}
finally
{
group.ShutdownGracefullyAsync().Wait(1000);
eventListener.Dispose();
}
}
static void Main() => RunClientAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Telnet.Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Telnet.Client")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ababfe48-551e-4c4b-8640-b334329d5c5d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{ABABFE48-551E-4C4B-8640-B334329D5C5D}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Telnet.Client</RootNamespace>
<AssemblyName>Telnet.Client</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="TelnetClientHandler.cs" />
<Compile Include="TelnetClientSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,23 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Client
{
using System;
using DotNetty.Transport.Channels;
public class TelnetClientHandler : SimpleChannelInboundHandler<string>
{
protected override void ChannelRead0(IChannelHandlerContext contex, string msg)
{
Console.WriteLine(msg);
}
public override void ExceptionCaught(IChannelHandlerContext contex, Exception e)
{
Console.WriteLine(DateTime.Now.Millisecond);
Console.WriteLine("{0}", e.StackTrace);
contex.CloseAsync();
}
}
}

Просмотреть файл

@ -0,0 +1,24 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Client
{
using System.Configuration;
using System.Net;
public static class TelnetClientSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static IPAddress Host => IPAddress.Parse(ConfigurationManager.AppSettings["host"]);
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
public static int Count => int.Parse(ConfigurationManager.AppSettings["count"]);
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="net452" />
</packages>

Просмотреть файл

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="ssl" value="True" />
<add key="port" value="8007" />
</appSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,75 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Server
{
using System;
using System.Diagnostics.Tracing;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Tls;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
class Program
{
static async Task RunServerAsync()
{
var eventListener = new ObservableEventListener();
eventListener.LogToConsole();
eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);
var bossGroup = new MultithreadEventLoopGroup(1);
var workerGroup = new MultithreadEventLoopGroup();
var STRING_ENCODER = new StringEncoder();
var STRING_DECODER = new StringDecoder();
var SERVER_HANDLER = new TelnetServerHandler();
X509Certificate2 tlsCertificate = null;
if (TelnetSettings.IsSsl)
{
tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
}
try
{
var bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler(LogLevel.INFO))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
IChannelPipeline pipeline = channel.Pipeline;
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
pipeline.AddLast(new DelimiterBasedFrameDecoder(8192, Delimiters.LineDelimiter()));
pipeline.AddLast(STRING_ENCODER, STRING_DECODER, SERVER_HANDLER);
}));
IChannel bootstrapChannel = await bootstrap.BindAsync(TelnetSettings.Port);
Console.ReadLine();
await bootstrapChannel.CloseAsync();
}
finally
{
Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
eventListener.Dispose();
}
}
static void Main() => RunServerAsync().Wait();
}
}

Просмотреть файл

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Telnet.Server")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Telnet.Server")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5543847a-8509-4646-8472-1e4450025fdf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

Просмотреть файл

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{5543847A-8509-4646-8472-1E4450025FDF}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Telnet.Server</RootNamespace>
<AssemblyName>Telnet.Server</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.EnterpriseLibrary.SemanticLogging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\..\packages\EnterpriseLibrary.SemanticLogging.2.0.1406.1\lib\net45\Microsoft.Practices.EnterpriseLibrary.SemanticLogging.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="TelnetSettings.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TelnetServerHandler.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="..\..\shared\dotnetty.com.pfx">
<Link>dotnetty.com.pfx</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\DotNetty.Buffers\DotNetty.Buffers.csproj">
<Project>{5de3c557-48bf-4cdb-9f47-474d343dd841}</Project>
<Name>DotNetty.Buffers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Codecs\DotNetty.Codecs.csproj">
<Project>{2abd244e-ef8f-460d-9c30-39116499e6e4}</Project>
<Name>DotNetty.Codecs</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Common\DotNetty.Common.csproj">
<Project>{de58fe41-5e99-44e5-86bc-fc9ed8761daf}</Project>
<Name>DotNetty.Common</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Handlers\DotNetty.Handlers.csproj">
<Project>{09628314-f44e-445e-9f0d-cbe33b736ac3}</Project>
<Name>DotNetty.Handlers</Name>
</ProjectReference>
<ProjectReference Include="..\..\src\DotNetty.Transport\DotNetty.Transport.csproj">
<Project>{8218c9ee-0a4a-432f-a12a-b54202f97b05}</Project>
<Name>DotNetty.Transport</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,60 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Server
{
using System;
using System.Net;
using DotNetty.Transport.Channels;
using System.Threading.Tasks;
public class TelnetServerHandler : SimpleChannelInboundHandler<String>
{
public override void ChannelActive(IChannelHandlerContext contex)
{
contex.WriteAsync(String.Format("Welcome to {0} !\r\n", Dns.GetHostName()));
contex.WriteAndFlushAsync(String.Format("It is {0} now !\r\n", DateTime.Now));
}
protected override void ChannelRead0(IChannelHandlerContext contex, string msg)
{
// Generate and write a response.
string response;
bool close = false;
if (String.IsNullOrEmpty(msg))
{
response = "Please type something.\r\n";
}
else if ("bye" == msg.ToLower())
{
response = "Have a good day!\r\n";
close = true;
}
else
{
response = "Did you say '" + msg + "'?\r\n";
}
var wait_close = contex.WriteAndFlushAsync(response);
if (close)
{
Task.WaitAll(wait_close);
contex.CloseAsync();
}
}
public override void ChannelReadComplete(IChannelHandlerContext contex)
{
contex.Flush();
}
public override void ExceptionCaught(IChannelHandlerContext contex, Exception e)
{
Console.WriteLine("{0}", e.StackTrace);
contex.CloseAsync();
}
public override bool IsSharable => true;
}
}

Просмотреть файл

@ -0,0 +1,21 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Telnet.Server
{
using System.Configuration;
public static class TelnetSettings
{
public static bool IsSsl
{
get
{
string ssl = System.Configuration.ConfigurationManager.AppSettings["ssl"];
return !string.IsNullOrEmpty(ssl) && bool.Parse(ssl);
}
}
public static int Port => int.Parse(ConfigurationManager.AppSettings["port"]);
}
}

Просмотреть файл

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EnterpriseLibrary.SemanticLogging" version="2.0.1406.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="5.0.8" targetFramework="net452" />
</packages>

Просмотреть файл

@ -56,7 +56,6 @@ namespace DotNetty.Codecs
}
output.Return();
}
base.ChannelRead(context, message);
}
/// <summary>

Просмотреть файл

@ -0,0 +1,50 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Transport.Channels
{
using DotNetty.Common.Utilities;
public abstract class SimpleChannelInboundHandler<I> : ChannelHandlerAdapter
{
readonly bool autoRelease;
protected SimpleChannelInboundHandler() : this(true)
{
}
protected SimpleChannelInboundHandler(bool autoRelease)
{
this.autoRelease = autoRelease;
}
public bool AcceptInboundMessage(object msg) => msg is I;
public override void ChannelRead(IChannelHandlerContext ctx, object msg)
{
bool release = true;
try
{
if (this.AcceptInboundMessage(msg))
{
I imsg = (I)msg;
this.ChannelRead0(ctx, imsg);
}
else
{
release = false;
ctx.FireChannelRead(msg);
}
}
finally
{
if (autoRelease && release)
{
ReferenceCountUtil.Release(msg);
}
}
}
protected abstract void ChannelRead0(IChannelHandlerContext ctx, I msg);
}
}

Просмотреть файл

@ -106,6 +106,7 @@
<Compile Include="Channels\IRecvByteBufAllocatorHandle.cs" />
<Compile Include="Channels\PendingWriteQueue.cs" />
<Compile Include="Channels\RejectedExecutionException.cs" />
<Compile Include="Channels\SimpleChannelInboundHandler.cs" />
<Compile Include="Channels\SingleThreadEventLoop.cs" />
<Compile Include="Channels\SkipAttribute.cs" />
<Compile Include="Channels\Sockets\AbstractSocketByteChannel.cs" />