diff --git a/simples/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj b/simples/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj index 3ed6803..b2d5bb2 100644 --- a/simples/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj +++ b/simples/JT808.Gateway.SimpleClient/JT808.Gateway.SimpleClient.csproj @@ -2,16 +2,16 @@ Exe - netcoreapp3.1 + net5.0 - - - - - - - + + + + + + + diff --git a/simples/JT808.Gateway.SimpleClient/Jobs/CallGrpcClientJob.cs b/simples/JT808.Gateway.SimpleClient/Jobs/CallGrpcClientJob.cs deleted file mode 100644 index 57fedd4..0000000 --- a/simples/JT808.Gateway.SimpleClient/Jobs/CallGrpcClientJob.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Grpc.Core; -using JT808.Gateway.GrpcService; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using System.Text.Json; - -namespace JT808.Gateway.SimpleClient.Jobs -{ - public class CallGrpcClientJob :IHostedService - { - private Channel channel; - private readonly ILogger Logger; - private Grpc.Core.Metadata AuthMetadata; - public CallGrpcClientJob( - ILoggerFactory loggerFactory) - { - Logger = loggerFactory.CreateLogger("CallGrpcClientJob"); - channel = new Channel("localhost:828", - ChannelCredentials.Insecure); - AuthMetadata = new Grpc.Core.Metadata(); - AuthMetadata.Add("token", "smallchi518"); - } - - public Task StartAsync(CancellationToken cancellationToken) - { - Task.Run(() => - { - while (!cancellationToken.IsCancellationRequested) - { - JT808Gateway.JT808GatewayClient jT808GatewayClient = new JT808Gateway.JT808GatewayClient(channel); - try - { - var result1 = jT808GatewayClient.GetTcpAtomicCounter(new Empty(), AuthMetadata); - var result2 = jT808GatewayClient.GetTcpSessionAll(new Empty(), AuthMetadata); - Logger.LogInformation($"[GetTcpAtomicCounter]:{JsonSerializer.Serialize(result1)}"); - Logger.LogInformation($"[GetTcpSessionAll]:{JsonSerializer.Serialize(result2)}"); - } - catch (Exception ex) - { - Logger.LogError(ex, "Call Grpc Error"); - } - try - { - var result1 = jT808GatewayClient.GetTcpAtomicCounter(new Empty()); - } - catch (RpcException ex) - { - Logger.LogError($"{ex.StatusCode.ToString()}-{ex.Message}"); - } - Thread.Sleep(3000); - } - }, cancellationToken); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - channel.ShutdownAsync(); - return Task.CompletedTask; - } - } -} diff --git a/simples/JT808.Gateway.SimpleClient/Jobs/CallHttpClientJob.cs b/simples/JT808.Gateway.SimpleClient/Jobs/CallHttpClientJob.cs new file mode 100644 index 0000000..4f0c0a3 --- /dev/null +++ b/simples/JT808.Gateway.SimpleClient/Jobs/CallHttpClientJob.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using System.Text.Json; +using JT808.Protocol.Extensions; +using Microsoft.Extensions.Options; +using JT808.Gateway.Abstractions.Configurations; +using JT808.Gateway.WebApiClientTool; + +namespace JT808.Gateway.SimpleClient.Jobs +{ + public class CallHttpClientJob :IHostedService + { + + private readonly ILogger Logger; + private JT808HttpClient jT808HttpClient; + public CallHttpClientJob( + ILoggerFactory loggerFactory, + JT808HttpClient jT808HttpClient) + { + Logger = loggerFactory.CreateLogger(); + this.jT808HttpClient = jT808HttpClient; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + Task.Run(async() => + { + while (!cancellationToken.IsCancellationRequested) + { + var result2 = await jT808HttpClient.GetTcpSessionAll(); + var result3 = await jT808HttpClient.UnificationSend(new Abstractions.Dtos.JT808UnificationSendRequestDto + { + TerminalPhoneNo= "123456789012", + HexData= "7E02000026123456789012007D02000000010000000200BA7F0E07E4F11C0028003C00001810151010100104000000640202007D01137E" + }); + Logger.LogInformation($"[GetTcpAtomicCounter]:{JsonSerializer.Serialize(result2)}"); + Logger.LogInformation($"[GetTcpSessionAll]:{JsonSerializer.Serialize(result3)}"); + Thread.Sleep(3000); + } + }, cancellationToken); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} diff --git a/simples/JT808.Gateway.SimpleClient/Program.cs b/simples/JT808.Gateway.SimpleClient/Program.cs index 69e7d84..53ee125 100644 --- a/simples/JT808.Gateway.SimpleClient/Program.cs +++ b/simples/JT808.Gateway.SimpleClient/Program.cs @@ -31,7 +31,7 @@ namespace JT808.Gateway.SimpleClient .AddClient(); services.AddHostedService(); services.AddHostedService(); - services.AddHostedService(); + services.AddHostedService(); }); await serverHostBuilder.RunConsoleAsync(); } diff --git a/simples/JT808.Gateway.SimpleClient/Services/Up2019Service.cs b/simples/JT808.Gateway.SimpleClient/Services/Up2019Service.cs index 1a8ba5e..3d8691a 100644 --- a/simples/JT808.Gateway.SimpleClient/Services/Up2019Service.cs +++ b/simples/JT808.Gateway.SimpleClient/Services/Up2019Service.cs @@ -23,7 +23,7 @@ namespace JT808.Gateway.SimpleClient.Services public async Task StartAsync(CancellationToken cancellationToken) { string sim = "22222222222"; - JT808TcpClient client1 = await jT808TcpClientFactory.Create(new JT808DeviceConfig(sim, "127.0.0.1", 808, JT808Version.JTT2019), cancellationToken); + JT808TcpClient client1 = await jT808TcpClientFactory.Create(new JT808DeviceConfig(sim, "127.0.0.1", 808, version:JT808Version.JTT2019), cancellationToken); await Task.Delay(2000); //1.终端注册 await client1.SendAsync(JT808MsgId.终端注册.Create2019(sim, new JT808_0x0100() diff --git a/simples/JT808.Gateway.SimpleQueueNotification/JT808.Gateway.SimpleQueueNotification.csproj b/simples/JT808.Gateway.SimpleQueueNotification/JT808.Gateway.SimpleQueueNotification.csproj index 2c99121..df2a182 100644 --- a/simples/JT808.Gateway.SimpleQueueNotification/JT808.Gateway.SimpleQueueNotification.csproj +++ b/simples/JT808.Gateway.SimpleQueueNotification/JT808.Gateway.SimpleQueueNotification.csproj @@ -1,7 +1,7 @@  - netcoreapp3.1 + net5.0 @@ -27,7 +27,7 @@ - - + + diff --git a/simples/JT808.Gateway.SimpleQueueServer/JT808.Gateway.SimpleQueueServer.csproj b/simples/JT808.Gateway.SimpleQueueServer/JT808.Gateway.SimpleQueueServer.csproj index 472c697..d2e7000 100644 --- a/simples/JT808.Gateway.SimpleQueueServer/JT808.Gateway.SimpleQueueServer.csproj +++ b/simples/JT808.Gateway.SimpleQueueServer/JT808.Gateway.SimpleQueueServer.csproj @@ -2,16 +2,16 @@ Exe - netcoreapp3.1 + net5.0 - - - - - - + + + + + + diff --git a/simples/JT808.Gateway.SimpleQueueServer/Program.cs b/simples/JT808.Gateway.SimpleQueueServer/Program.cs index d7f7dea..1e7a54e 100644 --- a/simples/JT808.Gateway.SimpleQueueServer/Program.cs +++ b/simples/JT808.Gateway.SimpleQueueServer/Program.cs @@ -29,14 +29,13 @@ namespace JT808.Gateway.SimpleQueueServer services.AddSingleton(); services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); services.AddJT808Configure() - .AddQueueGateway(hostContext.Configuration) + .AddGateway(hostContext.Configuration) .AddServerKafkaMsgProducer(hostContext.Configuration) .AddServerKafkaMsgReplyConsumer(hostContext.Configuration) .AddServerKafkaSessionProducer(hostContext.Configuration) .AddTcp() .AddUdp() - .AddGrpc() - .Builder(); + .AddHttp(); }); await serverHostBuilder.RunConsoleAsync(); diff --git a/simples/JT808.Gateway.SimpleQueueService/Impl/JT808QueueReplyMessageHandlerImpl.cs b/simples/JT808.Gateway.SimpleQueueService/Impl/JT808QueueReplyMessageHandlerImpl.cs index e7c200a..aa4ed04 100644 --- a/simples/JT808.Gateway.SimpleQueueService/Impl/JT808QueueReplyMessageHandlerImpl.cs +++ b/simples/JT808.Gateway.SimpleQueueService/Impl/JT808QueueReplyMessageHandlerImpl.cs @@ -1,36 +1,27 @@ using JT808.Gateway.Abstractions; +using JT808.Gateway.Abstractions.Configurations; using JT808.Protocol; +using JT808.Protocol.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; namespace JT808.Gateway.SimpleQueueService.Impl { - public class JT808QueueReplyMessageHandlerImpl : JT808QueueReplyMessageHandler + public class JT808QueueReplyMessageHandlerImpl : IJT808ReplyMessageHandler { - public JT808QueueReplyMessageHandlerImpl(IJT808Config jT808Config, IJT808MsgReplyProducer jT808MsgReplyProducer) : base(jT808Config, jT808MsgReplyProducer) - { - //添加自定义消息 - HandlerDict.Add(0x9999, Msg0x9999); - } + private ILogger logger; - /// - /// 重写消息 - /// - /// - /// - public override byte[] Msg0x0001(JT808HeaderPackage request) + public JT808QueueReplyMessageHandlerImpl(ILoggerFactory loggerFactory) { - return base.Msg0x0001(request); + logger = loggerFactory.CreateLogger(); } - /// - /// 自定义消息 - /// - /// - /// - public byte[] Msg0x9999(JT808HeaderPackage request) + public byte[] Processor(string TerminalNo, byte[] Data) { + logger.LogDebug($"JT808QueueReplyMessageHandlerImpl=>{TerminalNo},{Data.ToHexString()}"); return default; } } diff --git a/simples/JT808.Gateway.SimpleQueueService/JT808.Gateway.SimpleQueueService.csproj b/simples/JT808.Gateway.SimpleQueueService/JT808.Gateway.SimpleQueueService.csproj index 55dac23..c32b97b 100644 --- a/simples/JT808.Gateway.SimpleQueueService/JT808.Gateway.SimpleQueueService.csproj +++ b/simples/JT808.Gateway.SimpleQueueService/JT808.Gateway.SimpleQueueService.csproj @@ -2,22 +2,22 @@ Exe - netcoreapp3.1 + net5.0 - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/simples/JT808.Gateway.SimpleServer/Impl/JT808NormalReplyMessageHandlerImpl.cs b/simples/JT808.Gateway.SimpleServer/Impl/JT808MessageHandlerImpl.cs similarity index 82% rename from simples/JT808.Gateway.SimpleServer/Impl/JT808NormalReplyMessageHandlerImpl.cs rename to simples/JT808.Gateway.SimpleServer/Impl/JT808MessageHandlerImpl.cs index 3fb6604..1c5f0c2 100644 --- a/simples/JT808.Gateway.SimpleServer/Impl/JT808NormalReplyMessageHandlerImpl.cs +++ b/simples/JT808.Gateway.SimpleServer/Impl/JT808MessageHandlerImpl.cs @@ -1,33 +1,33 @@ using JT808.Gateway.Abstractions; +using JT808.Gateway.Abstractions.Configurations; using JT808.Gateway.MsgLogging; -using JT808.Gateway.Traffic; using JT808.Gateway.Transmit; using JT808.Protocol; using JT808.Protocol.Extensions; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; namespace JT808.Gateway.SimpleServer.Impl { - public class JT808NormalReplyMessageHandlerImpl : JT808NormalReplyMessageHandler + public class JT808MessageHandlerImpl : JT808MessageHandler { private readonly ILogger logger; - private readonly IJT808Traffic jT808Traffic; private readonly IJT808MsgLogging jT808MsgLogging; private readonly JT808TransmitService jT808TransmitService; - public JT808NormalReplyMessageHandlerImpl( + + public JT808MessageHandlerImpl( + ILoggerFactory loggerFactory, JT808TransmitService jT808TransmitService, IJT808MsgLogging jT808MsgLogging, - IJT808Traffic jT808Traffic, - ILoggerFactory loggerFactory, - IJT808Config jT808Config) : base(jT808Config) + IOptionsMonitor jT808ConfigurationOptionsMonitor, IJT808MsgProducer msgProducer, IJT808MsgReplyLoggingProducer msgReplyLoggingProducer, IJT808Config jT808Config) + : base(jT808ConfigurationOptionsMonitor, msgProducer, msgReplyLoggingProducer, jT808Config) { this.jT808TransmitService = jT808TransmitService; - this.jT808Traffic = jT808Traffic; this.jT808MsgLogging = jT808MsgLogging; - logger =loggerFactory.CreateLogger("JT808NormalReplyMessageHandlerImpl"); + logger = loggerFactory.CreateLogger(); //添加自定义消息 HandlerDict.Add(0x9999, Msg0x9999); } @@ -41,8 +41,6 @@ namespace JT808.Gateway.SimpleServer.Impl { //AOP 可以自定义添加一些东西:上下行日志、数据转发 logger.LogDebug("可以自定义添加一些东西:上下行日志、数据转发"); - //流量 - jT808Traffic.Increment(request.Header.TerminalPhoneNo, DateTime.Now.ToString("yyyyMMdd"), request.OriginalData.Length); var parameter = (request.Header.TerminalPhoneNo, request.OriginalData.ToArray()); //转发数据(可同步也可以使用队列进行异步) try diff --git a/simples/JT808.Gateway.SimpleServer/Impl/JT808MsgIdHandler.cs b/simples/JT808.Gateway.SimpleServer/Impl/JT808MsgIdHandler.cs index 3d62db0..0e19f58 100644 --- a/simples/JT808.Gateway.SimpleServer/Impl/JT808MsgIdHandler.cs +++ b/simples/JT808.Gateway.SimpleServer/Impl/JT808MsgIdHandler.cs @@ -1,22 +1,29 @@ -using JT808.Gateway.MsgIdHandler; -using JT808.Protocol.Extensions; +using JT808.Protocol.Extensions; +using JT808.Gateway.Abstractions; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; +using Microsoft.Extensions.Options; +using JT808.Gateway.Abstractions.Configurations; +using JT808.Protocol; namespace JT808.Gateway.SimpleServer.Impl { - public class JT808MsgIdHandler : IJT808MsgIdHandler + public class JT808MsgIdHandler : JT808MessageHandler { private readonly ILogger Logger; - public JT808MsgIdHandler(ILoggerFactory loggerFactory) + + public JT808MsgIdHandler( + ILoggerFactory loggerFactory, + IOptionsMonitor jT808ConfigurationOptionsMonitor, IJT808MsgProducer msgProducer, IJT808MsgReplyLoggingProducer msgReplyLoggingProducer, IJT808Config jT808Config) : base(jT808ConfigurationOptionsMonitor, msgProducer, msgReplyLoggingProducer, jT808Config) { - Logger = loggerFactory.CreateLogger("JT808MsgIdHandler"); + Logger = loggerFactory.CreateLogger(); } + public void Processor((string TerminalNo, byte[] Data) parameter) { - Logger.LogDebug($"{parameter.TerminalNo}-{parameter.Data.ToHexString()}"); + Logger.LogDebug($"JT808MsgIdHandler=>{parameter.TerminalNo}-{parameter.Data.ToHexString()}"); } } } diff --git a/simples/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj b/simples/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj index af9aa0f..e611ede 100644 --- a/simples/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj +++ b/simples/JT808.Gateway.SimpleServer/JT808.Gateway.SimpleServer.csproj @@ -2,20 +2,18 @@ Exe - netcoreapp3.1 + net5.0 - - - - - - - - - - - + + + + + + + + + diff --git a/simples/JT808.Gateway.SimpleServer/Jobs/TrafficJob.cs b/simples/JT808.Gateway.SimpleServer/Jobs/TrafficJob.cs deleted file mode 100644 index bd542c3..0000000 --- a/simples/JT808.Gateway.SimpleServer/Jobs/TrafficJob.cs +++ /dev/null @@ -1,48 +0,0 @@ -using JT808.Gateway.Traffic; -using JT808.Protocol.Enums; -using JT808.Protocol.Extensions; -using JT808.Protocol.MessageBody; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace JT808.Gateway.SimpleServer.Jobs -{ - public class TrafficJob : IHostedService - { - private readonly IJT808Traffic jT808Traffic; - private readonly ILogger Logger; - public TrafficJob( - ILoggerFactory loggerFactory, - IJT808Traffic jT808Traffic) - { - Logger = loggerFactory.CreateLogger("TrafficJob"); - this.jT808Traffic = jT808Traffic; - } - - public Task StartAsync(CancellationToken cancellationToken) - { - Task.Run(async () => - { - while (!cancellationToken.IsCancellationRequested) - { - await Task.Delay(2 * 1000); - foreach (var item in jT808Traffic.GetAll()) - { - Logger.LogDebug($"{item.Item1}-{item.Item2}"); - } - } - }, cancellationToken); - return Task.CompletedTask; - } - - public Task StopAsync(CancellationToken cancellationToken) - { - return Task.CompletedTask; - } - } -} diff --git a/simples/JT808.Gateway.SimpleServer/Program.cs b/simples/JT808.Gateway.SimpleServer/Program.cs index 378a25b..530d3c4 100644 --- a/simples/JT808.Gateway.SimpleServer/Program.cs +++ b/simples/JT808.Gateway.SimpleServer/Program.cs @@ -1,8 +1,6 @@ using JT808.Gateway.Abstractions.Enums; using JT808.Gateway.ReplyMessage; using JT808.Gateway.MsgLogging; -using JT808.Gateway.Traffic; -using JT808.Gateway.MsgIdHandler; using JT808.Gateway.SessionNotice; using JT808.Protocol; using Microsoft.Extensions.Configuration; @@ -16,7 +14,6 @@ using JT808.Gateway.SimpleServer.Impl; using JT808.Gateway.SimpleServer.Services; using JT808.Gateway.Abstractions; using JT808.Gateway.Transmit; -using JT808.Gateway.SimpleServer.Jobs; namespace JT808.Gateway.SimpleServer { @@ -44,18 +41,15 @@ namespace JT808.Gateway.SimpleServer services.AddSingleton(); services.AddSingleton(); services.AddJT808Configure() - .AddNormalGateway(hostContext.Configuration) - .ReplaceNormalReplyMessageHandler() + .AddGateway(hostContext.Configuration) + .AddMessageHandler() .AddMsgLogging() - .AddTraffic() .AddSessionNotice() .AddTransmit(hostContext.Configuration) .AddTcp() .AddUdp() - .AddGrpc() + .AddHttp() .Builder(); - //流量统计 - services.AddHostedService(); }); await serverHostBuilder.RunConsoleAsync(); diff --git a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs index 72c5efc..997839c 100644 --- a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs +++ b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Configs/ClientBenchmarkOptions.cs @@ -19,6 +19,16 @@ namespace JT808.Gateway.CleintBenchmark.Configs /// 100000-200000-300000 /// public int DeviceTemplate { get; set; } = 0; + /// + /// 本地绑定IP地址 + /// 适用多网卡绑定 + /// + public string LocalIPAddress { get; set; } + /// + /// 本地绑定IP端口 + /// 适用多网卡绑定 + /// + public int LocalPort { get; set; } public ClientBenchmarkOptions Value =>this; } } diff --git a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs index 5a43622..857e250 100644 --- a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs +++ b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/Services/CleintBenchmarkHostedService.cs @@ -51,7 +51,9 @@ namespace JT808.Gateway.CleintBenchmark.Services string deviceNo = ((int)state + 1 + clientBenchmarkOptions.DeviceTemplate).ToString(); var client = await jT808TcpClientFactory.Create(new JT808DeviceConfig(deviceNo, clientBenchmarkOptions.IP, - clientBenchmarkOptions.Port), cancellationToken); + clientBenchmarkOptions.Port, + clientBenchmarkOptions.LocalIPAddress, + clientBenchmarkOptions.LocalPort + (int)state + 1), cancellationToken); while (!cancellationToken.IsCancellationRequested) { try @@ -80,6 +82,7 @@ namespace JT808.Gateway.CleintBenchmark.Services await Task.Delay(clientBenchmarkOptions.Interval); } }, i); + Thread.Sleep(500); } return Task.CompletedTask; } diff --git a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/appsettings.json b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/appsettings.json index 7611940..36b0bef 100644 --- a/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/appsettings.json +++ b/src/JT808.Gateway.Benchmark/JT808.Gateway.CleintBenchmark/appsettings.json @@ -13,11 +13,11 @@ } }, "AllowedHosts": "*", - //"urls": "http://*:15004;", + "urls": "http://*:5000;", "ClientBenchmarkOptions": { - "IP": "127.0.0.1", + "IP": "172.18.0.7", "Port": 808, - "DeviceCount": 100, + "DeviceCount": 1, "Interval": 1000, "DeviceTemplate": 100000 //需要多台机器同时访问,那么可以根据这个避开重复终端号 100000-200000-300000 } diff --git a/src/JT808.Gateway.Client/JT808ClientExtensions.cs b/src/JT808.Gateway.Client/JT808ClientExtensions.cs index 2700b00..4fbecb3 100644 --- a/src/JT808.Gateway.Client/JT808ClientExtensions.cs +++ b/src/JT808.Gateway.Client/JT808ClientExtensions.cs @@ -20,6 +20,7 @@ namespace JT808.Gateway.Client jT808ClientBuilderDefault.JT808Builder.Services.AddSingleton(); jT808ClientBuilderDefault.JT808Builder.Services.AddSingleton(); jT808ClientBuilderDefault.JT808Builder.Services.AddSingleton(); + jT808ClientBuilderDefault.JT808Builder.Services.AddHostedService(); return jT808ClientBuilderDefault; } @@ -29,12 +30,6 @@ namespace JT808.Gateway.Client jT808ClientBuilder.JT808Builder.Services.Replace(new ServiceDescriptor(typeof(IJT808MessageProducer), typeof(TJT808MessageProducer), ServiceLifetime.Singleton)); return jT808ClientBuilder; } - - public static IJT808ClientBuilder AddClientRetry(this IJT808ClientBuilder jT808ClientBuilder) - { - jT808ClientBuilder.JT808Builder.Services.AddHostedService(); - return jT808ClientBuilder; - } public static IJT808ClientBuilder AddClientReport(this IJT808ClientBuilder jT808ClientBuilder) { diff --git a/src/JT808.Gateway.Client/JT808DeviceConfig.cs b/src/JT808.Gateway.Client/JT808DeviceConfig.cs index 7169005..27e28cb 100644 --- a/src/JT808.Gateway.Client/JT808DeviceConfig.cs +++ b/src/JT808.Gateway.Client/JT808DeviceConfig.cs @@ -9,12 +9,14 @@ namespace JT808.Gateway.Client { public class JT808DeviceConfig { - public JT808DeviceConfig(string terminalPhoneNo, string tcpHost,int tcpPort, JT808Version version= JT808Version.JTT2013) + public JT808DeviceConfig(string terminalPhoneNo, string tcpHost,int tcpPort, string localIPAddress=null,int localPort=0, JT808Version version= JT808Version.JTT2013) { TerminalPhoneNo = terminalPhoneNo; TcpHost = tcpHost; TcpPort = tcpPort; Version = version; + LocalIPAddress = localIPAddress; + LocalPort = localPort; } public JT808Version Version { get; private set; } public string TerminalPhoneNo { get; private set; } @@ -29,5 +31,7 @@ namespace JT808.Gateway.Client /// public bool AutoReconnection { get; set; } = true; public IJT808MsgSNDistributed MsgSNDistributed { get; } + public string LocalIPAddress { get; set; } + public int LocalPort { get; set; } } } diff --git a/src/JT808.Gateway.Client/JT808TcpClient.cs b/src/JT808.Gateway.Client/JT808TcpClient.cs index 80079f8..d801191 100644 --- a/src/JT808.Gateway.Client/JT808TcpClient.cs +++ b/src/JT808.Gateway.Client/JT808TcpClient.cs @@ -46,11 +46,17 @@ namespace JT808.Gateway.Client producer = serviceProvider.GetRequiredService(); RetryBlockingCollection = serviceProvider.GetRequiredService(); } - public async ValueTask ConnectAsync(EndPoint remoteEndPoint) + public async ValueTask ConnectAsync() { + var remoteEndPoint = new IPEndPoint(IPAddress.Parse(DeviceConfig.TcpHost), DeviceConfig.TcpPort); clientSocket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { + if (!string.IsNullOrEmpty(DeviceConfig.LocalIPAddress)) + { + IPAddress localIPAddress = IPAddress.Parse(DeviceConfig.LocalIPAddress); + clientSocket.Bind(new IPEndPoint(localIPAddress, DeviceConfig.LocalPort)); + } await clientSocket.ConnectAsync(remoteEndPoint); await Task.Factory.StartNew(async()=> { while (!heartbeatCTS.IsCancellationRequested) diff --git a/src/JT808.Gateway.Client/JT808TcpClientFactory.cs b/src/JT808.Gateway.Client/JT808TcpClientFactory.cs index 60ba143..500fd44 100644 --- a/src/JT808.Gateway.Client/JT808TcpClientFactory.cs +++ b/src/JT808.Gateway.Client/JT808TcpClientFactory.cs @@ -40,7 +40,7 @@ namespace JT808.Gateway.Client else { JT808TcpClient jT808TcpClient = new JT808TcpClient(deviceConfig, serviceProvider); - var successed= await jT808TcpClient.ConnectAsync(new IPEndPoint(IPAddress.Parse(deviceConfig.TcpHost), deviceConfig.TcpPort)); + var successed= await jT808TcpClient.ConnectAsync(); if (successed) { jT808TcpClient.StartAsync(cancellationToken); diff --git a/src/JT808.Gateway.Client/Services/JT808RetryClientHostedService.cs b/src/JT808.Gateway.Client/Services/JT808RetryClientHostedService.cs index dba8a83..effba55 100644 --- a/src/JT808.Gateway.Client/Services/JT808RetryClientHostedService.cs +++ b/src/JT808.Gateway.Client/Services/JT808RetryClientHostedService.cs @@ -15,7 +15,7 @@ using System.Threading.Tasks; namespace JT808.Gateway.Client.Services { - internal class JT808RetryClientHostedService : BackgroundService + internal class JT808RetryClientHostedService : IHostedService { private readonly IJT808TcpClientFactory jT808TcpClientFactory; @@ -33,37 +33,46 @@ namespace JT808.Gateway.Client.Services RetryBlockingCollection = retryBlockingCollection; } - protected override async Task ExecuteAsync(CancellationToken stoppingToken) + public Task StartAsync(CancellationToken cancellationToken) { - foreach (var item in RetryBlockingCollection.RetryBlockingCollection.GetConsumingEnumerable(stoppingToken)) - { - try + Task.Run(async()=> { + foreach (var item in RetryBlockingCollection.RetryBlockingCollection.GetConsumingEnumerable(cancellationToken)) { - jT808TcpClientFactory.Remove(item); - if (item.AutoReconnection) + try { - var result = await jT808TcpClientFactory.Create(item, stoppingToken); - if (result != null) + jT808TcpClientFactory.Remove(item); + if (item.AutoReconnection) { - if (logger.IsEnabled(LogLevel.Information)) + var result = await jT808TcpClientFactory.Create(item, cancellationToken); + if (result != null) { - logger.LogInformation($"Retry Success-{JsonSerializer.Serialize(item)}"); + if (logger.IsEnabled(LogLevel.Information)) + { + logger.LogInformation($"Retry Success-{JsonSerializer.Serialize(item)}"); + } } - } - else - { - if (logger.IsEnabled(LogLevel.Warning)) + else { - logger.LogWarning($"Retry Fail-{JsonSerializer.Serialize(item)}"); + if (logger.IsEnabled(LogLevel.Warning)) + { + logger.LogWarning($"Retry Fail-{JsonSerializer.Serialize(item)}"); + } } } } + catch (Exception ex) + { + logger.LogError(ex, $"Retry Error-{JsonSerializer.Serialize(item)}"); + await Task.Delay(TimeSpan.FromSeconds(5)); + } } - catch (Exception ex) - { - logger.LogError(ex, $"Retry Error-{JsonSerializer.Serialize(item)}"); - } - } + }, cancellationToken); + return Task.CompletedTask; + } + + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; } } }