NettyClient.cs 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Runtime.Remoting.Contexts;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using DotNetty.Buffers;
  11. using DotNetty.Codecs;
  12. using DotNetty.Handlers.Timeout;
  13. using DotNetty.Transport.Bootstrapping;
  14. using DotNetty.Transport.Channels;
  15. using DotNetty.Transport.Channels.Sockets;
  16. using DotNettyFrom.common;
  17. using DotNettyFrom.config;
  18. using DotNettyFrom.util;
  19. namespace DotNettyFrom.netty
  20. {
  21. public class NettyClient
  22. {
  23. private MultithreadEventLoopGroup _group;
  24. private NettyClientHandler _clientHandler;
  25. private static bool _isSendLoginCmd = true;
  26. public void StartNetty(string host, int port, bool isSendLoginCmd = true)
  27. {
  28. _isSendLoginCmd = isSendLoginCmd;
  29. IPAddress hostIp = IPAddress.Parse(host);
  30. RunClientAsync(hostIp, port);
  31. DataModel.ReceCollection.Add(new UIInfoModel("StartNetty:开始尝试连接").setSendType(SystemConfig.DebugType));
  32. }
  33. private async void RunClientAsync(IPAddress HostIP, int Port)
  34. {
  35. _group = new MultithreadEventLoopGroup();
  36. var bootstrap = new Bootstrap();
  37. bootstrap
  38. .Group(_group)
  39. .Channel<TcpSocketChannel>()
  40. .Option(ChannelOption.TcpNodelay, true)
  41. .Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
  42. {
  43. IChannelPipeline pipeline = channel.Pipeline;
  44. /*pipeline.AddLast(new LengthFieldBasedFrameDecoder(ushort.MaxValue,
  45. SystemConfig.LengthFieldOffset,
  46. SystemConfig.LengthFieldLength,
  47. SystemConfig.LengthAdjustment,
  48. SystemConfig.InitialBytesToStrip));*/
  49. pipeline.AddLast(new IdleStateHandler(SystemConfig.ReaderIdleTimeSeconds,
  50. SystemConfig.WriterIdleTimeSeconds,
  51. SystemConfig.AllIdleTimeSeconds));
  52. _clientHandler = new NettyClientHandler();
  53. pipeline.AddLast(_clientHandler);
  54. }));
  55. try
  56. {
  57. await bootstrap.ConnectAsync(new IPEndPoint(HostIP, Port));
  58. }
  59. catch (Exception e)
  60. {
  61. //连接出错,服务器没开启....
  62. //Console.WriteLine(e);
  63. DataModel.ReceCollection.Add(new UIInfoModel("远程服务器连接失败." + e.Message).setAction(-1)
  64. .setSendType(SystemConfig.DebugType));
  65. await _group.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
  66. }
  67. }
  68. public void SendData(string hex)
  69. {
  70. if (NettyClientHandler.Context.Channel.Active)
  71. {
  72. IByteBuffer msg = AryUtil.Hex2IByteBuffer(hex);
  73. NettyClientHandler.Context.WriteAndFlushAsync(msg);
  74. DataModel.ReceCollection.Add(new UIInfoModel("发送", hex).setSendType(SystemConfig.SendType));
  75. }
  76. else
  77. {
  78. DataModel.ReceCollection.Add(new UIInfoModel("SendData:连接已经断开").setSendType(SystemConfig.DebugType));
  79. }
  80. }
  81. public void StopNetty()
  82. {
  83. NettyClientHandler.Context?.Channel.CloseAsync();
  84. _group?.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromSeconds(1));
  85. _group = null;
  86. NettyClientHandler.Context = null;
  87. _clientHandler = null;
  88. DataModel.ReceCollection.Add(new UIInfoModel("StopNetty:停止连接"));
  89. }
  90. public class NettyClientHandler : ChannelHandlerAdapter
  91. {
  92. internal static IChannelHandlerContext Context;
  93. public override void ChannelActive(IChannelHandlerContext context)
  94. {
  95. Context = context;
  96. DataModel.ReceCollection.Add(new UIInfoModel("ChannelActive:连接成功").setAction(1)
  97. .setSendType(SystemConfig.DebugType));
  98. if (_isSendLoginCmd)
  99. {
  100. //发送登录指令
  101. IByteBuffer cmd =
  102. AryUtil.Hex2IByteBuffer("7e7e7e0000000000018200143839383630324731313931353530333339393137e3");
  103. context.WriteAndFlushAsync(cmd);
  104. DataModel.ReceCollection.Add(
  105. new UIInfoModel("发送登录", "7e7e7e0000000000018200143839383630324731313931353530333339393137e3")
  106. .setAction(1).setSendType(SystemConfig.SendType));
  107. }
  108. }
  109. public override void ChannelRead(IChannelHandlerContext context, object message)
  110. {
  111. if (message is IByteBuffer buffer)
  112. {
  113. string recCmd = AryUtil.ByteBuffer2Hex(buffer);
  114. DataModel.ReceCollection.Add(new UIInfoModel("收到", recCmd));
  115. }
  116. }
  117. public override void ChannelReadComplete(IChannelHandlerContext context)
  118. {
  119. base.ChannelReadComplete(context);
  120. }
  121. public override void UserEventTriggered(IChannelHandlerContext context, object evt)
  122. {
  123. base.UserEventTriggered(context, evt);
  124. }
  125. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  126. {
  127. base.ExceptionCaught(context, exception);
  128. Console.WriteLine(exception.Message);
  129. DataModel.ReceCollection.Add(new UIInfoModel("ExceptionCaught:" + exception.Message).setAction(3)
  130. .setSendType(SystemConfig.DebugType));
  131. }
  132. public override void ChannelInactive(IChannelHandlerContext context)
  133. {
  134. base.ChannelInactive(context);
  135. DataModel.ReceCollection.Add(new UIInfoModel("ChannelInactive:" + context.Channel)
  136. .setAction(2).setSendType(SystemConfig.DebugType));
  137. }
  138. }
  139. }
  140. }