NettyClient.cs 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using DotNetty.Buffers;
  10. using DotNetty.Handlers.Timeout;
  11. using DotNetty.Transport.Bootstrapping;
  12. using DotNetty.Transport.Channels;
  13. using DotNetty.Transport.Channels.Sockets;
  14. using DotNettyFrom.common;
  15. namespace DotNettyFrom.netty
  16. {
  17. public class NettyClient
  18. {
  19. public static IChannelHandlerContext Context;
  20. private MultithreadEventLoopGroup _group;
  21. private NettyClientHandler _clientHandler;
  22. public void StartNetty(string host, int port)
  23. {
  24. IPAddress hostIp = IPAddress.Parse(host);
  25. RunClientAsync(hostIp, port);
  26. }
  27. private async void RunClientAsync(IPAddress HostIP, int Port)
  28. {
  29. _group = new MultithreadEventLoopGroup();
  30. var 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("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 10, 2, 1, 0));
  39. pipeline.AddLast("idle", new IdleStateHandler(10, 20, 15));
  40. _clientHandler = new NettyClientHandler();
  41. pipeline.AddLast("echo", _clientHandler);
  42. }));
  43. try
  44. {
  45. await bootstrap.ConnectAsync(new IPEndPoint(HostIP, Port));
  46. }
  47. catch (Exception e)
  48. {
  49. //连接出错,服务器没开启....
  50. Console.WriteLine(e);
  51. await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
  52. }
  53. }
  54. public void SendData(string hex)
  55. {
  56. if (Context.Channel.Active)
  57. {
  58. IByteBuffer msg = Unpooled.Buffer(128);
  59. byte[] messageBytes = Encoding.UTF8.GetBytes(DateTime.Now.ToLongDateString());
  60. msg.WriteBytes(messageBytes);
  61. Context.Channel.WriteAndFlushAsync(msg);
  62. }
  63. else
  64. {
  65. DataModel.ReceCollection.Add(new UIInfoModel("连接已断开", ""));
  66. }
  67. }
  68. public void StopNetty()
  69. {
  70. Context?.Channel.CloseAsync();
  71. _group?.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
  72. _group = null;
  73. Context = null;
  74. _clientHandler = null;
  75. }
  76. class NettyClientHandler : ChannelHandlerAdapter
  77. {
  78. public override void ChannelActive(IChannelHandlerContext context)
  79. {
  80. Context = context;
  81. IByteBuffer msg = Unpooled.Buffer(128);
  82. byte[] messageBytes = Encoding.UTF8.GetBytes(DateTime.Now.ToLongDateString());
  83. msg.WriteBytes(messageBytes);
  84. context.WriteAndFlushAsync(msg);
  85. DataModel.ReceCollection.Add(new UIInfoModel("", DateTime.Now.ToLongDateString() + "channeiActive"));
  86. }
  87. public override void ChannelRead(IChannelHandlerContext context, object message)
  88. {
  89. if (message is IByteBuffer buffer)
  90. {
  91. string abc = buffer.ToString(Encoding.UTF8);
  92. DataModel.ReceCollection.Add(new UIInfoModel("", "收到:-----------" + abc));
  93. }
  94. // IByteBuffer msg = Unpooled.Buffer(128);
  95. // byte[] messageBytes = Encoding.UTF8.GetBytes(DateTime.Now.ToLongDateString());
  96. // msg.WriteBytes(messageBytes);
  97. // context.WriteAndFlushAsync(msg);
  98. }
  99. public override void ChannelReadComplete(IChannelHandlerContext context)
  100. {
  101. base.ChannelReadComplete(context);
  102. }
  103. public override void UserEventTriggered(IChannelHandlerContext context, object evt)
  104. {
  105. base.UserEventTriggered(context, evt);
  106. }
  107. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  108. {
  109. base.ExceptionCaught(context, exception);
  110. Console.WriteLine(exception.Message);
  111. DataModel.ReceCollection.Add(new UIInfoModel("", "ExceptionCaught:" + exception.Message));
  112. }
  113. public override void ChannelInactive(IChannelHandlerContext context)
  114. {
  115. base.ChannelInactive(context);
  116. DataModel.ReceCollection.Add(new UIInfoModel("", "ChannelInactive"));
  117. }
  118. }
  119. }
  120. }