mirror of
https://github.com/Azure/DotNetty.git
synced 2026-10-28 04:14:29 +08:00
Motivation: Some important SSL Stream settings are hidden in the TlsHandler class Modifications: SSLStream is provided by user now via factory method; TLS settings extended Results: More advanced scenarios, like X509 client authentication, are possible to do now
73 lines
2.7 KiB
C#
73 lines
2.7 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
|
|
namespace Echo.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 (EchoClientSettings.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 LengthFieldPrepender(2));
|
|
pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
|
|
|
|
pipeline.AddLast(new EchoClientHandler());
|
|
}));
|
|
|
|
IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(EchoClientSettings.Host, EchoClientSettings.Port));
|
|
|
|
Console.ReadLine();
|
|
|
|
await bootstrapChannel.CloseAsync();
|
|
}
|
|
finally
|
|
{
|
|
group.ShutdownGracefullyAsync().Wait(1000);
|
|
eventListener.Dispose();
|
|
}
|
|
}
|
|
|
|
static void Main() => RunClientAsync().Wait();
|
|
}
|
|
} |