TelnetClientHandler.cs 7.7 KB

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