TelnetServerHandler.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using DotNetty.Buffers;
  10. using DotNetty.Transport.Channels;
  11. using Team.Communicate.Data;
  12. using Team.Communicate.EventArg;
  13. using Team.Utility;
  14. namespace Team.Communicate.Handlers
  15. {
  16. public class TelnetServerHandler : ChannelHandlerAdapter// SimpleChannelInboundHandler<string>
  17. {
  18. public event EventHandler<TcpStateEventArgs> ConnectionEvent;
  19. private List<string> UseUnRegisterKeys = new();
  20. private readonly ConcurrentDictionary<string, Func<string, IChannelHandlerContext, ValueTask<string>>> _registerCenterCollection;
  21. public Action<string, IChannelHandlerContext> UseUnRegisterAction;
  22. public Encoding Encoding { get; set; }
  23. public string _endWith{ get; private set; }
  24. public TelnetServerHandler()
  25. {
  26. _registerCenterCollection = new ConcurrentDictionary<string, Func<string, IChannelHandlerContext, ValueTask<string>>>();
  27. }
  28. internal void SetEncoding(Encoding encoding)
  29. {
  30. Encoding = encoding;
  31. }
  32. public void Register(string id, Func<string, IChannelHandlerContext, ValueTask<string>> func)
  33. {
  34. if (_registerCenterCollection.ContainsKey(id))
  35. {
  36. _registerCenterCollection[id] = func;
  37. return;
  38. }
  39. _registerCenterCollection.TryAdd(id, func);
  40. }
  41. public void UnRegister(string id)
  42. {
  43. if (!_registerCenterCollection.ContainsKey(id)) return;
  44. _registerCenterCollection.TryRemove(id, out var func);
  45. }
  46. public void ClearAllRegister()
  47. {
  48. _registerCenterCollection.Clear();
  49. }
  50. public override void ChannelActive(IChannelHandlerContext context)
  51. {
  52. base.ChannelActive(context);
  53. var iPEndPoint = (IPEndPoint) context.Channel.RemoteAddress;
  54. var ipAddress = iPEndPoint.Address;
  55. if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
  56. {
  57. ipAddress = ipAddress.MapToIPv4();
  58. }
  59. var port = iPEndPoint.Port;
  60. OnConnectionChanged(ipAddress.ToString(), port, true);
  61. }
  62. /// <summary>
  63. /// use unregister message
  64. /// </summary>
  65. internal void SetUseUnRegisterKeys(List<string> keys)
  66. {
  67. UseUnRegisterKeys = keys;
  68. }
  69. public override void ChannelInactive(IChannelHandlerContext context)
  70. {
  71. base.ChannelInactive(context);
  72. var iPEndPoint = (IPEndPoint)context.Channel.RemoteAddress;
  73. var ipAddress = iPEndPoint.Address;
  74. if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
  75. {
  76. ipAddress = ipAddress.MapToIPv4();
  77. }
  78. var port = iPEndPoint.Port;
  79. OnConnectionChanged(ipAddress.ToString(), port, false);
  80. }
  81. internal void SetEndWith(string endWith)
  82. {
  83. _endWith = endWith;
  84. }
  85. public async override void ChannelRead(IChannelHandlerContext context, object data)
  86. {
  87. //base.ChannelRead(ctx, msg);
  88. string msg = string.Empty;
  89. if (data is IByteBuffer buffer)
  90. {
  91. LogUtil.WriteInfo("Received from client: " + buffer.ToString(Encoding));
  92. msg = buffer.ToString(Encoding);
  93. }
  94. var ipAddress = ((IPEndPoint)context.Channel.RemoteAddress).Address;
  95. if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
  96. {
  97. ipAddress = ipAddress.MapToIPv4();
  98. }
  99. LogUtil.WriteInfo($"客户端{ipAddress}发生消息:{msg}");
  100. msg = msg.Replace("\0", string.Empty);
  101. if (!context.Channel.Active)
  102. {
  103. LogUtil.WriteInfo($"客户端{ipAddress}断开未完成对话");
  104. return;
  105. }
  106. if (!_registerCenterCollection.ContainsKey(msg))
  107. {
  108. foreach (var key in UseUnRegisterKeys)
  109. {
  110. if (msg.Contains(key))
  111. {
  112. LogUtil.WriteInfo($"客户端{ipAddress}发送需要使用的未注册消息");
  113. UseUnRegisterAction?.BeginInvoke(msg, context, null, null);
  114. return;
  115. }
  116. }
  117. LogUtil.WriteInfo($"客户端{ipAddress}发送未注册消息");
  118. try
  119. {
  120. var stringBuilder = new StringBuilder();
  121. stringBuilder.Append("NotRegisterMessage,");
  122. stringBuilder.Append(msg);
  123. stringBuilder.Append(_endWith);
  124. var bytes= Encoding.GetBytes(stringBuilder.ToString());
  125. var sendBytes = Unpooled.Buffer(256);
  126. sendBytes.WriteBytes(bytes);
  127. await context.WriteAndFlushAsync(sendBytes);
  128. }
  129. catch (Exception e)
  130. {
  131. LogUtil.WriteInfo("发送数据时发生了错误" + e);
  132. }
  133. return;
  134. }
  135. LogUtil.WriteInfo("等待处理消息");
  136. var invoker = _registerCenterCollection[msg];
  137. invoker.BeginInvoke(msg, context, async obj =>
  138. {
  139. string response = await invoker.EndInvoke(obj);
  140. if (string.IsNullOrEmpty(msg))
  141. {
  142. response = "Please type something.";
  143. }
  144. Thread.Sleep(10000);
  145. response += _endWith;
  146. var bytes1 = Encoding.GetBytes(response);
  147. var sendBytes1 = Unpooled.Buffer(5);
  148. sendBytes1.WriteBytes(bytes1);
  149. await context.WriteAndFlushAsync(sendBytes1);
  150. }, context);
  151. }
  152. public override void Read(IChannelHandlerContext context)
  153. {
  154. base.Read(context);
  155. }
  156. public override void ChannelReadComplete(IChannelHandlerContext context)
  157. {
  158. try
  159. {
  160. context.Flush();
  161. base.ChannelReadComplete(context);
  162. }
  163. catch (Exception e)
  164. {
  165. LogUtil.WriteInfo(e.StackTrace);
  166. }
  167. }
  168. public async override void ExceptionCaught(IChannelHandlerContext context, Exception e)
  169. {
  170. LogUtil.WriteInfo(e.StackTrace);
  171. try
  172. {
  173. await context.CloseAsync();
  174. }
  175. catch (Exception se)
  176. {
  177. LogUtil.WriteInfo(se.StackTrace);
  178. }
  179. }
  180. public override void ChannelUnregistered(IChannelHandlerContext context)
  181. {
  182. base.ChannelUnregistered(context);
  183. }
  184. private void OnConnectionChanged(string ip, int port, bool connected)
  185. {
  186. var args = new TcpStateEventArgs(new TcpConnection(ip, port)
  187. {
  188. Connected = connected
  189. });
  190. ConnectionEvent?.Invoke(this, args);
  191. }
  192. public override bool IsSharable => true;
  193. }
  194. }