You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

77 lines
3.4 KiB

  1. using DotNetty.Transport.Bootstrapping;
  2. using DotNetty.Transport.Channels;
  3. using DotNetty.Transport.Channels.Sockets;
  4. using Polly;
  5. using System;
  6. using System.Linq;
  7. using System.Collections.Generic;
  8. using System.Net;
  9. using System.Text;
  10. using Microsoft.Extensions.Logging;
  11. namespace JT808.Gateway.BusinessServices.Transmit.Handlers
  12. {
  13. public class ClientConnectionHandler : ChannelHandlerAdapter
  14. {
  15. private readonly Bootstrap bootstrap;
  16. public Dictionary<string, IChannel> channeldic;
  17. private readonly ILogger<ClientConnectionHandler> logger;
  18. public ClientConnectionHandler(Bootstrap bootstrap,
  19. Dictionary<string, IChannel> channeldic,
  20. ILoggerFactory loggerFactory)
  21. {
  22. this.bootstrap = bootstrap;
  23. this.channeldic = channeldic;
  24. logger = loggerFactory.CreateLogger<ClientConnectionHandler>();
  25. }
  26. public override void ChannelInactive(IChannelHandlerContext context)
  27. {
  28. Policy.HandleResult<bool>(context.Channel.Open)
  29. .WaitAndRetryForeverAsync(retryAttempt =>
  30. {
  31. return retryAttempt > 20 ? TimeSpan.FromSeconds(Math.Pow(2, 50)) : TimeSpan.FromSeconds(Math.Pow(2, retryAttempt));//超过重试20次,之后重试都是接近12个小时重试一次
  32. },
  33. (exception, timespan, ctx) =>
  34. {
  35. logger.LogError($"服务端断开{context.Channel.RemoteAddress},重试结果{exception.Result},重试次数{timespan},下次重试间隔(s){ctx.TotalSeconds}");
  36. })
  37. .ExecuteAsync(async () =>
  38. {
  39. try
  40. {
  41. var oldChannel = channeldic.FirstOrDefault(m => m.Value == context.Channel);
  42. if (default(KeyValuePair<string, IChannel>).Equals(oldChannel))
  43. {
  44. if(logger.IsEnabled( LogLevel.Debug))
  45. logger.LogDebug($"服务器已经删除了{oldChannel.Key}远程服务器配置");
  46. return true;
  47. }
  48. var channel = await bootstrap.ConnectAsync(context.Channel.RemoteAddress);
  49. channeldic.Remove(oldChannel.Key);
  50. channeldic.Add(oldChannel.Key, channel);
  51. return channel.Open;
  52. }
  53. catch (Exception ex)
  54. {
  55. logger.LogError($"服务端断开后{context.Channel.RemoteAddress},重连异常:{ex}");
  56. return false;
  57. }
  58. });
  59. }
  60. public override void ChannelRead(IChannelHandlerContext context, object message)
  61. {
  62. if (logger.IsEnabled(LogLevel.Debug))
  63. {
  64. logger.LogError($"服务端返回消息{message}");
  65. }
  66. }
  67. public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
  68. {
  69. logger.LogError($"服务端Exception: {exception}");
  70. context.CloseAsync();
  71. }
  72. }
  73. }