Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

72 řádky
3.4 KiB

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