ClientDemo.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Text;
  3. using System.Threading.Tasks;
  4. using DotNetty.Transport.Bootstrapping;
  5. using DotNetty.Transport.Channels;
  6. using DotNetty.Transport.Channels.Sockets;
  7. using DotNetty.Codecs;
  8. using System.Net;
  9. using System.Security.Cryptography.X509Certificates;
  10. using System.IO;
  11. using DotNetty.Handlers.Tls;
  12. using System.Net.Security;
  13. using System.Threading;
  14. namespace nettyCommunication
  15. {
  16. public class ClientDemo
  17. {
  18. public static async Task RunClientAsync()
  19. {
  20. var group = new MultithreadEventLoopGroup();
  21. X509Certificate2 cert = null;
  22. string targetHost = null;
  23. if (ClientSettings.IsSsl)
  24. {
  25. cert = new X509Certificate2(Path.Combine(ConfigurationTools.ProcessDirectory, "dotnetty.com.pfx"), "password");
  26. targetHost = cert.GetNameInfo(X509NameType.DnsName, false);
  27. }
  28. try
  29. {
  30. Bootstrap bootstrap = new Bootstrap();
  31. bootstrap
  32. .Group(group)
  33. .Channel<TcpSocketChannel>()
  34. .Option(ChannelOption.TcpNodelay, true)
  35. .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
  36. {
  37. IChannelPipeline pipeline = channel.Pipeline;
  38. pipeline.AddLast(new ClientDemoHandler());
  39. }));
  40. IChannel bootstrapChannel = await bootstrap.ConnectAsync(new IPEndPoint(ClientSettings.Host, ClientSettings.Port));
  41. Console.WriteLine("连接已建立,已执行完channelActive,如果buffer有数据,然后切换到ChannelRead");
  42. Console.WriteLine("ClientDemo RunClientAsync()方法中等待输入:切换到ChannelRead.请输入任意字符:");
  43. //Console.WriteLine("next执行连接关闭");
  44. await bootstrapChannel.CloseAsync();
  45. }
  46. finally
  47. {
  48. // Console.WriteLine("连接不能关闭呀");
  49. //group.ShutdownGracefullyAsync().Wait(1000);
  50. //await group.ShutdownGracefullyAsync();
  51. }
  52. }
  53. }
  54. }