Ver código fonte

1.去掉Json.Net的引用改为微软自带的Json库

2.完善tcp、udp、webapi的测试用例
3.增加CI/CD配置
4.修改文档内容
tags/v2.2.2
smallchi 5 anos atrás
pai
commit
a53db63c23
39 arquivos alterados com 586 adições e 815 exclusões
  1. +21
    -0
      .travis.yml
  2. +9
    -9
      README.md
  3. +0
    -31
      src/JT808.DotNetty.Core/Configurations/JT808ClientConfiguration.cs
  4. +35
    -0
      src/JT808.DotNetty.Core/Converters/ByteArrayHexTextJsonConverter.cs
  5. +0
    -29
      src/JT808.DotNetty.Core/Converters/JsonByteArrayHexConverter.cs
  6. +0
    -26
      src/JT808.DotNetty.Core/Converters/JsonIPAddressConverter.cs
  7. +0
    -32
      src/JT808.DotNetty.Core/Converters/JsonIPEndPointConverter.cs
  8. +12
    -12
      src/JT808.DotNetty.Core/Handlers/JT808MsgIdHttpHandlerBase.cs
  9. +13
    -7
      src/JT808.DotNetty.Core/Impls/JT808DefaultChannelId.cs
  10. +1
    -1
      src/JT808.DotNetty.Core/Impls/JT808MsgReplyConsumerDefaultImpl.cs
  11. +1
    -1
      src/JT808.DotNetty.Core/JT808.DotNetty.Core.csproj
  12. +2
    -45
      src/JT808.DotNetty.Core/JT808CoreDotnettyExtensions.cs
  13. +0
    -50
      src/JT808.DotNetty.Core/JT808SimpleTcpClient.cs
  14. +0
    -48
      src/JT808.DotNetty.Core/JT808SimpleUdpClient.cs
  15. +13
    -6
      src/JT808.DotNetty.Core/Services/JT808SessionService.cs
  16. +3
    -1
      src/JT808.DotNetty.Core/Services/JT808UnificationSendService.cs
  17. +10
    -0
      src/JT808.DotNetty.Tcp/JT808TcpDotnettyExtensions.cs
  18. +3
    -8
      src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808.DotNetty.Core.Test.csproj
  19. +19
    -28
      src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808TcpSessionManagerTest.cs
  20. +1
    -12
      src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/SeedTcpSession.cs
  21. +0
    -37
      src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/TestBase.cs
  22. +0
    -39
      src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/appsettings.json
  23. +4
    -9
      src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808.DotNetty.Tcp.Test.csproj
  24. +55
    -62
      src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808SessionServiceTest.cs
  25. +0
    -76
      src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808UnificationTcpSendServiceTest.cs
  26. +50
    -23
      src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/TestBase.cs
  27. +0
    -21
      src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/appsettings.json
  28. +3
    -14
      src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808.DotNetty.Udp.Test.csproj
  29. +61
    -59
      src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808SessionServiceTest.cs
  30. +0
    -76
      src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808UnificationUdpSendServiceTest.cs
  31. +47
    -20
      src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/TestBase.cs
  32. +0
    -22
      src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/appsettings.json
  33. +194
    -0
      src/JT808.DotNetty.Tests/JT808.DotNetty.WebApi.Test/Handlers/JT808WebAPIServerHandlerTest.cs
  34. +1
    -1
      src/JT808.DotNetty.Tests/JT808.DotNetty.WebApi.Test/JT808.DotNetty.WebApi.Test.csproj
  35. +8
    -0
      src/JT808.DotNetty.Udp/JT808UdpDotnettyExtensions.cs
  36. +3
    -4
      src/JT808.DotNetty.WebApi/Handlers/JT808MsgIdDefaultWebApiHandler.cs
  37. +8
    -5
      src/JT808.DotNetty.WebApi/Handlers/JT808WebAPIServerHandler.cs
  38. +8
    -0
      src/JT808.DotNetty.WebApi/JT808WebApiDotnettyExtensions.cs
  39. +1
    -1
      src/Version.props

+ 21
- 0
.travis.yml Ver arquivo

@@ -0,0 +1,21 @@
language: csharp
solution: JT808.DotNetty.sln
dotnet: 3.0.100
os: linux
mono: none
dist: trusty2
script:
- dotnet restore src/JT808.DotNetty.sln
- dotnet build src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808.DotNetty.Core.Test.csproj
- dotnet test src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808.DotNetty.Core.Test.csproj
- dotnet build src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808.DotNetty.Tcp.Test.csproj
- dotnet test src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808.DotNetty.Tcp.Test.csproj
- dotnet build src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808.DotNetty.Udp.Test.csproj
- dotnet test src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808.DotNetty.Udp.Test.csproj
- dotnet build src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808.DotNetty.Udp.Test.csproj
- dotnet test src/JT808.DotNetty.Tests/JT808.DotNetty.WebApi.Test/JT808.DotNetty.WebApi.Test.csproj
after_success:
- echo successful build!
branches:
only:
- master

+ 9
- 9
README.md Ver arquivo

@@ -12,7 +12,7 @@

[玩一玩压力测试](https://github.com/SmallChi/JT808DotNetty/blob/master/doc/README.md)

[![MIT Licence](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE)
[![MIT Licence](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/SmallChi/JT808DotNetty/blob/master/LICENSE)[![Build Status](https://travis-ci.org/SmallChi/JT808DotNetty.svg?branch=master)](https://travis-ci.org/SmallChi/JT808DotNetty)

## 新网关的优势:

@@ -108,15 +108,15 @@ static async Task Main(string[] args)
//.AddJT808ServerKafkaMsgReplyConsumer(hostContext.Configuration)
//.AddJT808ServerKafkaSessionProducer(hostContext.Configuration)
//.Builder();
//webapi客户端调用
//services.AddHttpApi<IJT808DotNettyWebApi>().ConfigureHttpApiConfig((c, p) =>
//使用微软自带的webapi客户端
//services.AddHttpClient("jt808webapi", c =>
//{
// c.HttpHost = new Uri("http://localhost:828/jt808api/");
// c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
// c.LoggerFactory = p.GetRequiredService<ILoggerFactory>();
//});
//var client = services.BuildServiceProvider().GetRequiredService<IJT808DotNettyWebApi>();
//var result = client.GetTcpAtomicCounter().InvokeAsync().Result;
// c.BaseAddress = new Uri("http://localhost:828/");
// c.DefaultRequestHeaders.Add("token", "123456);
//})
//.AddTypedClient<JT808HttpClient>();
//var client = services.BuildServiceProvider().GetRequiredService<JT808HttpClient>();
//var result = client.GetTcpAtomicCounter();
});

await serverHostBuilder.RunConsoleAsync();


+ 0
- 31
src/JT808.DotNetty.Core/Configurations/JT808ClientConfiguration.cs Ver arquivo

@@ -1,31 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace JT808.DotNetty.Core.Configurations
{
public class JT808ClientConfiguration
{
public string Host { get; set; }

public int Port { get; set; }

private EndPoint endPoint;

public EndPoint EndPoint
{
get
{
if (endPoint == null)
{
if (IPAddress.TryParse(Host, out IPAddress ip))
{
endPoint = new IPEndPoint(ip, Port);
}
}
return endPoint;
}
}
}
}

+ 35
- 0
src/JT808.DotNetty.Core/Converters/ByteArrayHexTextJsonConverter.cs Ver arquivo

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace JT808.DotNetty.Core.JsonConvert
{
/// <summary>
///
/// ref:https://github.com/dotnet/corefx/blob/release/3.0/src/System.Text.Json/tests/Serialization/CustomConverterTests.Array.cs
/// </summary>
public class ByteArrayHexTextJsonConverter : JsonConverter<byte[]>
{
public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
//string hexJson = reader.get();
var hexJson = reader.GetString();
var list = new List<byte>();
foreach (string str in hexJson.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries))
{
list.Add(Convert.ToByte(str, 16));
}
return list.ToArray();
}

public override void Write(Utf8JsonWriter writer, byte[] value, JsonSerializerOptions options)
{
var hexString = string.Join(" ", (value).Select(p => p.ToString("X2")));
writer.WriteStringValue(hexString);
}
}
}

+ 0
- 29
src/JT808.DotNetty.Core/Converters/JsonByteArrayHexConverter.cs Ver arquivo

@@ -1,29 +0,0 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JT808.DotNetty.Core.Converters
{
class ByteArrayHexConverter : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType == typeof(byte[]);

public override bool CanRead => false;
public override bool CanWrite => true;

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => throw new NotImplementedException();

private readonly string _separator;

public ByteArrayHexConverter(string separator = " ") => _separator = separator;

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var hexString = string.Join(_separator, ((byte[])value).Select(p => p.ToString("X2")));
writer.WriteValue(hexString);
}
}
}

+ 0
- 26
src/JT808.DotNetty.Core/Converters/JsonIPAddressConverter.cs Ver arquivo

@@ -1,26 +0,0 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;

namespace JT808.DotNetty.Core.Converters
{
public class JsonIPAddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IPAddress));
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return IPAddress.Parse((string)reader.Value);
}
}
}

+ 0
- 32
src/JT808.DotNetty.Core/Converters/JsonIPEndPointConverter.cs Ver arquivo

@@ -1,32 +0,0 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net;

namespace JT808.DotNetty.Core.Converters
{
public class JsonIPEndPointConverter: JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(IPEndPoint));
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IPEndPoint ep = (IPEndPoint)value;
JObject jo = new JObject();
jo.Add("Host", JToken.FromObject(ep.Address, serializer));
jo.Add("Port", ep.Port);
jo.WriteTo(writer);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
IPAddress address = jo["Host"].ToObject<IPAddress>(serializer);
int port = (int)jo["Port"];
return new IPEndPoint(address, port);
}
}
}

+ 12
- 12
src/JT808.DotNetty.Core/Handlers/JT808MsgIdHttpHandlerBase.cs Ver arquivo

@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using JT808.DotNetty.Abstractions.Dtos;
using JT808.DotNetty.Core.Metadata;
using Newtonsoft.Json;

namespace JT808.DotNetty.Core.Handlers
{
@@ -42,7 +42,7 @@ namespace JT808.DotNetty.Core.Handlers

protected JT808HttpResponse CreateJT808HttpResponse(dynamic dynamicObject)
{
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dynamicObject));
byte[] data = JsonSerializer.SerializeToUtf8Bytes(dynamicObject);
return new JT808HttpResponse()
{
Data = data
@@ -51,51 +51,51 @@ namespace JT808.DotNetty.Core.Handlers

public JT808HttpResponse DefaultHttpResponse()
{
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new JT808DefaultResultDto()));
byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808DefaultResultDto());
return new JT808HttpResponse(json);
}

public JT808HttpResponse EmptyHttpResponse()
{
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new JT808ResultDto<string>()
byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto<string>()
{
Code = JT808ResultCode.Empty,
Message = "内容为空",
Data = "Content Empty"
}));
});
return new JT808HttpResponse(json);
}

public JT808HttpResponse NotFoundHttpResponse()
{
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new JT808ResultDto<string>()
byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto<string>()
{
Code = JT808ResultCode.NotFound,
Message = "没有该服务",
Data = "没有该服务"
}));
});
return new JT808HttpResponse(json);
}

public JT808HttpResponse AuthFailHttpResponse()
{
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new JT808ResultDto<string>()
byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto<string>()
{
Code = JT808ResultCode.AuthFail,
Message = "token认证失败",
Data = "token认证失败"
}));
});
return new JT808HttpResponse(json);
}

public JT808HttpResponse ErrorHttpResponse(Exception ex)
{
byte[] json = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new JT808ResultDto<string>()
byte[] json = JsonSerializer.SerializeToUtf8Bytes(new JT808ResultDto<string>()
{
Code = JT808ResultCode.Error,
Message = JsonConvert.SerializeObject(ex),
Message = ex.StackTrace,
Data = ex.Message
}));
});
return new JT808HttpResponse(json);
}
}


src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808DefaultChannelId.cs → src/JT808.DotNetty.Core/Impls/JT808DefaultChannelId.cs Ver arquivo

@@ -3,16 +3,22 @@ using System;
using System.Collections.Generic;
using System.Text;

namespace JT808.DotNetty.Core.Test
namespace JT808.DotNetty.Core.Impls
{
public class JT808DefaultChannelId : IChannelId
/// <summary>
/// 仅测试用
/// </summary>
internal class JT808DefaultChannelId : IChannelId
{
private string Id {
get
{
return Guid.NewGuid().ToString("N");
}
public JT808DefaultChannelId()
{
Id= Guid.NewGuid().ToString("N");
}
public JT808DefaultChannelId(string id)
{
Id = id;
}
private string Id { get;}

public string AsLongText()
{

+ 1
- 1
src/JT808.DotNetty.Core/Impls/JT808MsgReplyConsumerDefaultImpl.cs Ver arquivo

@@ -61,7 +61,7 @@ namespace JT808.DotNetty.Core.Impls
}
}
}
catch (Exception ex)
catch
{

}


+ 1
- 1
src/JT808.DotNetty.Core/JT808.DotNetty.Core.csproj Ver arquivo

@@ -27,8 +27,8 @@
<PackageReference Include="DotNetty.Codecs" Version="0.6.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Microsoft.Extensions.Options" Version="3.0.0" />
<PackageReference Include="System.Text.Json" Version="4.6.0" />
</ItemGroup>

<ItemGroup>


+ 2
- 45
src/JT808.DotNetty.Core/JT808CoreDotnettyExtensions.cs Ver arquivo

@@ -1,6 +1,5 @@
using JT808.DotNetty.Abstractions;
using JT808.DotNetty.Core.Configurations;
using JT808.DotNetty.Core.Converters;
using JT808.DotNetty.Core.Impls;
using JT808.DotNetty.Core.Interfaces;
using JT808.DotNetty.Core.Services;
@@ -11,14 +10,12 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("JT808.DotNetty.Core.Test")]
[assembly: InternalsVisibleTo("JT808.DotNetty.Tcp.Test")]
[assembly: InternalsVisibleTo("JT808.DotNetty.Udp.Test")]
[assembly: InternalsVisibleTo("JT808.DotNetty.WebApiTest")]
[assembly: InternalsVisibleTo("JT808.DotNetty.Tcp")]
[assembly: InternalsVisibleTo("JT808.DotNetty.Udp")]
[assembly: InternalsVisibleTo("JT808.DotNetty.WebApi")]
@@ -26,37 +23,8 @@ namespace JT808.DotNetty.Core
{
public static class JT808CoreDotnettyExtensions
{
static JT808CoreDotnettyExtensions()
public static IJT808NettyBuilder AddJT808NettyCore(this IJT808Builder jt808Builder, IConfiguration configuration)
{
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
//日期类型默认格式化处理
settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
settings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//空值处理
settings.NullValueHandling = NullValueHandling.Ignore;
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
settings.Converters.Add(new JsonIPAddressConverter());
settings.Converters.Add(new JsonIPEndPointConverter());
settings.Converters.Add(new ByteArrayHexConverter());
return settings;
});
}

public static IJT808NettyBuilder AddJT808NettyCore(this IJT808Builder jt808Builder, IConfiguration configuration, Newtonsoft.Json.JsonSerializerSettings settings=null)
{
if (settings != null)
{
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
settings.Converters.Add(new JsonIPAddressConverter());
settings.Converters.Add(new JsonIPEndPointConverter());
settings.Converters.Add(new ByteArrayHexConverter());
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return settings;
});
}
IJT808NettyBuilder nettyBuilder = new JT808NettyBuilderDefault(jt808Builder);
nettyBuilder.JT808Builder.Services.Configure<JT808Configuration>(configuration.GetSection("JT808Configuration"));
nettyBuilder.JT808Builder.Services.TryAddSingleton<JT808AtomicCounterServiceFactory>();
@@ -71,19 +39,8 @@ namespace JT808.DotNetty.Core
return nettyBuilder;
}

public static IJT808NettyBuilder AddJT808NettyCore(this IJT808Builder jt808Builder, Action<JT808Configuration> jt808Options, Newtonsoft.Json.JsonSerializerSettings settings = null)
public static IJT808NettyBuilder AddJT808NettyCore(this IJT808Builder jt808Builder, Action<JT808Configuration> jt808Options)
{
if (settings != null)
{
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
settings.Converters.Add(new JsonIPAddressConverter());
settings.Converters.Add(new JsonIPEndPointConverter());
settings.Converters.Add(new ByteArrayHexConverter());
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return settings;
});
}
IJT808NettyBuilder nettyBuilder = new JT808NettyBuilderDefault(jt808Builder);
nettyBuilder.JT808Builder.Services.Configure(jt808Options);
nettyBuilder.JT808Builder.Services.TryAddSingleton<JT808AtomicCounterServiceFactory>();


+ 0
- 50
src/JT808.DotNetty.Core/JT808SimpleTcpClient.cs Ver arquivo

@@ -1,50 +0,0 @@
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace JT808.DotNetty.Core
{
internal class JT808SimpleTcpClient
{
private TcpClient tcpClient;

public JT808SimpleTcpClient(IPEndPoint remoteAddress)
{
tcpClient = new TcpClient();
tcpClient.Connect(remoteAddress);
Task.Run(()=> {
while (true)
{
try
{
byte[] buffer = new byte[100];
tcpClient.GetStream().Read(buffer, 0, 100);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + string.Join(" ", buffer));
}
catch
{

}
Thread.Sleep(1000);
}
});
}

public void WriteAsync(byte[] data)
{
tcpClient.GetStream().WriteAsync(data, 0, data.Length);
}

public void Down()
{
tcpClient.Close();
}
}
}

+ 0
- 48
src/JT808.DotNetty.Core/JT808SimpleUdpClient.cs Ver arquivo

@@ -1,48 +0,0 @@
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace JT808.DotNetty.Core
{
internal class JT808SimpleUdpClient
{
private UdpClient udpClient;

public JT808SimpleUdpClient(IPEndPoint remoteAddress)
{
udpClient = new UdpClient();
udpClient.Connect(remoteAddress);
Task.Run(() =>
{
while (true)
{
try
{
string tmp = string.Join(" ", udpClient.Receive(ref remoteAddress));
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + tmp);
Thread.Sleep(1000);
}
catch
{


}
Thread.Sleep(1000);
}
});
}

public void WriteAsync(byte[] data)
{
udpClient.SendAsync(data, data.Length);
}

public void Down()
{
udpClient.Close();
}
}
}

+ 13
- 6
src/JT808.DotNetty.Core/Services/JT808SessionService.cs Ver arquivo

@@ -1,4 +1,5 @@
using System;
using System.Text.Json;
using System.Collections.Generic;
using System.Linq;
using JT808.DotNetty.Abstractions.Dtos;
@@ -35,7 +36,7 @@ namespace JT808.DotNetty.Core.Services
{
resultDto.Data = null;
resultDto.Code = JT808ResultCode.Error;
resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
resultDto.Message = ex.Message;
}
return resultDto;
}
@@ -58,7 +59,7 @@ namespace JT808.DotNetty.Core.Services
{
resultDto.Data = null;
resultDto.Code = JT808ResultCode.Error;
resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
resultDto.Message = ex.Message;
}
return resultDto;
}
@@ -75,21 +76,27 @@ namespace JT808.DotNetty.Core.Services
{
session.Channel.CloseAsync();
}
resultDto.Code = JT808ResultCode.Ok;
resultDto.Data = true;
}
else
{
resultDto.Code = JT808ResultCode.Empty;
resultDto.Data = false;
resultDto.Message = "Session Empty";
}
resultDto.Code = JT808ResultCode.Ok;
resultDto.Data = true;
}
catch (AggregateException ex)
{
resultDto.Data = false;
resultDto.Code = 500;
resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
resultDto.Message = ex.Message;
}
catch (Exception ex)
{
resultDto.Data = false;
resultDto.Code = JT808ResultCode.Error;
resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
resultDto.Message = ex.Message;
}
return resultDto;
}


+ 3
- 1
src/JT808.DotNetty.Core/Services/JT808UnificationSendService.cs Ver arquivo

@@ -1,7 +1,9 @@
using JT808.DotNetty.Abstractions.Dtos;
using JT808.DotNetty.Core;
using JT808.DotNetty.Core.Interfaces;
using JT808.DotNetty.Core.Session;
using System;
using System.Text.Json;

namespace JT808.DotNetty.Internal
{
@@ -37,7 +39,7 @@ namespace JT808.DotNetty.Internal
{
resultDto.Data = false;
resultDto.Code = JT808ResultCode.Error;
resultDto.Message = Newtonsoft.Json.JsonConvert.SerializeObject(ex);
resultDto.Message = ex.Message;
}
return resultDto;
}


+ 10
- 0
src/JT808.DotNetty.Tcp/JT808TcpDotnettyExtensions.cs Ver arquivo

@@ -21,5 +21,15 @@ namespace JT808.DotNetty.Tcp
jT808NettyBuilder.JT808Builder.Services.AddHostedService<JT808TcpServerHost>();
return jT808NettyBuilder;
}

internal static IServiceCollection AddJT808TcpNettyHostTest(this IServiceCollection serviceDescriptors)
{
serviceDescriptors.TryAddScoped<JT808TcpConnectionHandler>();
serviceDescriptors.TryAddScoped<JT808TcpEncoder>();
serviceDescriptors.TryAddScoped<JT808TcpDecoder>();
serviceDescriptors.TryAddScoped<JT808TcpServerHandler>();
serviceDescriptors.AddHostedService<JT808TcpServerHost>();
return serviceDescriptors;
}
}
}

+ 3
- 8
src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808.DotNetty.Core.Test.csproj Ver arquivo

@@ -11,18 +11,13 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\JT808.DotNetty.Core\JT808.DotNetty.Core.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>

+ 19
- 28
src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/JT808TcpSessionManagerTest.cs Ver arquivo

@@ -1,47 +1,34 @@
using DotNetty.Transport.Channels.Embedded;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JT808.DotNetty.Core.Impls;
using System.Threading;
using Xunit;

namespace JT808.DotNetty.Core.Test
{
[TestClass]
public class JT808SessionManagerTest: SeedTcpSession
{
[TestMethod]
public void Test1()
[Fact]
public void AddTest()
{
var no = "test150";
var channel = new EmbeddedChannel(new JT808DefaultChannelId());
jT80TcpSessionManager.TryAdd(no,channel);
Thread.Sleep(1000);
jT80TcpSessionManager.Heartbeat(no);
Assert.NotNull(jT80TcpSessionManager.GetTcpSessionByTerminalPhoneNo(no));
}

[TestMethod]
public void Test2()
[Fact]
public void RemoveTest()
{
var no = "test151";
var channel = new EmbeddedChannel(new JT808DefaultChannelId());
jT80TcpSessionManager.TryAdd(no, channel);
var sessionInfo = jT80TcpSessionManager.RemoveSession(no);
Assert.AreEqual(no, sessionInfo.TerminalPhoneNo);
}

[TestMethod]
public void Test3()
{
var realSessionInfos = jT80TcpSessionManager.GetAll();
Assert.Equal(no, sessionInfo.TerminalPhoneNo);
}

[TestMethod]
public void Test4()
{
var realSessionCount = jT80TcpSessionManager.SessionCount;
}

[TestMethod]
public void Test5()
[Fact]
public void OneChannelToManyDeviceTest1()
{
//转发过来的数据 1:n 一个通道对应多个设备
var no = "test1";
@@ -56,13 +43,14 @@ namespace JT808.DotNetty.Core.Test
jT80TcpSessionManager.TryAdd(no3,channel);
jT80TcpSessionManager.TryAdd(no4,channel);
var removeSession = jT80TcpSessionManager.RemoveSession(no);
Assert.AreEqual(no, removeSession.TerminalPhoneNo);
Assert.AreEqual(channel, removeSession.Channel);
Assert.AreEqual(channel.Id, removeSession.Channel.Id);
Assert.Equal(no, removeSession.TerminalPhoneNo);
Assert.Equal(channel, removeSession.Channel);
Assert.Equal(1,channel.Id.CompareTo(removeSession.Channel.Id));
}

[TestMethod]
public void Test6()

[Fact]
public void OneChannelToManyDeviceTest2()
{
//转发过来的数据 1:n 一个通道对应多个设备
var no = "test61";
@@ -78,6 +66,9 @@ namespace JT808.DotNetty.Core.Test
jT80TcpSessionManager.TryAdd(no3,channel2);
jT80TcpSessionManager.TryAdd(no4,channel2);
jT80TcpSessionManager.RemoveSessionByChannel(channel1);
Assert.Null(jT80TcpSessionManager.GetTcpSessionByTerminalPhoneNo(no));
Assert.Null(jT80TcpSessionManager.GetTcpSessionByTerminalPhoneNo(no1));
Assert.Null(jT80TcpSessionManager.GetTcpSessionByTerminalPhoneNo(no2));
}
}
}

+ 1
- 12
src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/SeedTcpSession.cs Ver arquivo

@@ -1,15 +1,14 @@
using DotNetty.Transport.Channels.Embedded;
using JT808.DotNetty.Core.Impls;
using JT808.DotNetty.Core.Session;
using JT808.DotNetty.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace JT808.DotNetty.Core.Test
{
[TestClass]
public class SeedTcpSession
{
public JT808SessionManager jT80TcpSessionManager = new JT808SessionManager(
@@ -24,15 +23,5 @@ namespace JT808.DotNetty.Core.Test
jT80TcpSessionManager.TryAdd(i.ToString(),channel);
}
}

[TestMethod]
public void Init()
{
for (var i = 0; i < 10; i++)
{
var channel = new EmbeddedChannel(new JT808DefaultChannelId());
jT80TcpSessionManager.TryAdd(i.ToString(), channel);
}
}
}
}

+ 0
- 37
src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/TestBase.cs Ver arquivo

@@ -1,37 +0,0 @@
using JT808.Protocol;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace JT808.DotNetty.Core.Test
{
public class TestBase
{
public static IServiceProvider ServiceProvider;

static TestBase()
{
var serverHostBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddJT808Configure()
.AddJT808NettyCore(hostContext.Configuration);
});
var build = serverHostBuilder.Build();
build.Start();
ServiceProvider = build.Services;

}
}
}

+ 0
- 39
src/JT808.DotNetty.Tests/JT808.DotNetty.Core.Test/appsettings.json Ver arquivo

@@ -1,39 +0,0 @@
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Trace"
}
},
"Console": {
"LogLevel": {
"Default": "Trace"
}
}
},
"JT808Configuration": {
"Port": 6565,
"SourcePackageDispatcherClientConfigurations": [
{
"Host": "127.0.0.1",
"Port": 6655
},
{
"Host": "127.0.0.1",
"Port": 6656
}
],
"ForwardingRemoteAddress": [
{
"Host": "127.0.0.1",
"Port": 6561
},
{
"Host": "127.0.0.1",
"Port": 6562
}
],
"RedisHost": "127.0.0.1:6379"
}
}

+ 4
- 9
src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808.DotNetty.Tcp.Test.csproj Ver arquivo

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
@@ -11,18 +11,13 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\JT808.DotNetty.Tcp\JT808.DotNetty.Tcp.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>

+ 55
- 62
src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808SessionServiceTest.cs Ver arquivo

@@ -8,88 +8,81 @@ using System.Text;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using JT808.Protocol.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JT808.DotNetty.Core.Session;
using JT808.DotNetty.Abstractions.Dtos;
using JT808.Protocol.MessageBody;
using Xunit;
using System.Linq;
using JT808.DotNetty.Core.Codecs;
using DotNetty.Buffers;

namespace JT808.DotNetty.Tcp.Test
{
[TestClass]
public class JT808SessionServiceTest:TestBase,IDisposable
public class JT808SessionServiceTest:TestBase
{
static IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6565);
JT808SimpleTcpClient SimpleTcpClient1;
JT808SimpleTcpClient SimpleTcpClient2;
JT808SimpleTcpClient SimpleTcpClient3;
JT808SimpleTcpClient SimpleTcpClient4;
JT808SimpleTcpClient SimpleTcpClient5;
List<string> TNos = new List<string> {
"123456789001",
"123456789002",
"123456789003",
"123456789004",
"123456789005"
};

public JT808SessionServiceTest()
{
SimpleTcpClient1 = new JT808SimpleTcpClient(endPoint);
SimpleTcpClient2 = new JT808SimpleTcpClient(endPoint);
SimpleTcpClient3 = new JT808SimpleTcpClient(endPoint);
SimpleTcpClient4 = new JT808SimpleTcpClient(endPoint);
SimpleTcpClient5 = new JT808SimpleTcpClient(endPoint);
// 心跳会话包
JT808Package jT808Package1 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789001");
SimpleTcpClient1.WriteAsync(JT808Serializer.Serialize(jT808Package1));

// 心跳会话包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789002");
SimpleTcpClient2.WriteAsync(JT808Serializer.Serialize(jT808Package2));

// 心跳会话包
JT808Package jT808Package3 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789003");
SimpleTcpClient3.WriteAsync(JT808Serializer.Serialize(jT808Package3));

// 心跳会话包
JT808Package jT808Package4 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789004");
SimpleTcpClient4.WriteAsync(JT808Serializer.Serialize(jT808Package4));

// 心跳会话包
JT808Package jT808Package5 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789005");
SimpleTcpClient5.WriteAsync(JT808Serializer.Serialize(jT808Package5));
Thread.Sleep(1000);
SeedSession(TNos.ToArray());
}

public void Dispose()
{
SimpleTcpClient1.Down();
SimpleTcpClient2.Down();
SimpleTcpClient3.Down();
SimpleTcpClient4.Down();
SimpleTcpClient5.Down();
}

[TestMethod]
public void Test1()
[Fact]
public void GetTcpAllTest()
{
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
var result = jT808SessionServiceDefaultImpl.GetTcpAll();
Thread.Sleep(5000);
var tons = result.Data.Select(s => s.TerminalPhoneNo).ToList();
foreach (var item in TNos)
{
Assert.Contains(item, tons);
}
Assert.Equal(JT808ResultCode.Ok, result.Code);
}

[TestMethod]
public void Test2()
[Fact]
public void RemoveByTerminalPhoneNoTest()
{
string tno = "123456789006";
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
var result1 = jT808SessionServiceDefaultImpl.GetTcpAll();
var result2 = jT808SessionServiceDefaultImpl.RemoveByTerminalPhoneNo("123456789001");
var result3 = jT808SessionServiceDefaultImpl.GetTcpAll();
SeedSession(tno);
var result1 = jT808SessionServiceDefaultImpl.RemoveByTerminalPhoneNo(tno);
Assert.Equal(JT808ResultCode.Ok, result1.Code);
Assert.True(result1.Data);
var result2 = jT808SessionServiceDefaultImpl.GetTcpAll();
Assert.Equal(JT808ResultCode.Ok, result2.Code);
Assert.DoesNotContain(tno, result2.Data.Select(s => s.TerminalPhoneNo));
}

[TestMethod]
public void Test3()
[Fact]
public void SendTest()
{
// 判断通道是否关闭
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
JT808SessionManager jT808TcpSessionManager = ServiceProvider.GetService<JT808SessionManager>();
var result1 = jT808SessionServiceDefaultImpl.GetTcpAll();
SimpleTcpClient1.Down();
Thread.Sleep(5000);
var session = jT808TcpSessionManager.GetSessionByTerminalPhoneNo("123456789001");
Thread.Sleep(100000);
//"126 131 0 0 13 18 52 86 120 144 1 0 11 5 115 109 97 108 108 99 104 105 32 53 49 56 24 126"
var jT808UnificationSendService = ServiceProvider.GetService<IJT808UnificationSendService>();
string no = "123456789001";
// 文本信息包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.文本信息下发.Create(no, new JT808_0x8300
{
TextFlag = 5,
TextInfo = "smallchi 518"
});
var data = JT808Serializer.Serialize(jT808Package2);
JT808ResultDto<bool> jt808Result = jT808UnificationSendService.Send(no, data);
Assert.Equal(JT808ResultCode.Ok, jt808Result.Code);
Assert.True(jt808Result.Data);
if (Channels.TryGetValue(no, out var channel))
{
var package = channel.ReadOutbound<IByteBuffer>();
byte[] recevie = new byte[package.Capacity];
package.ReadBytes(recevie);
Assert.Equal(data, recevie);
}
}
}
}

+ 0
- 76
src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/JT808UnificationTcpSendServiceTest.cs Ver arquivo

@@ -1,76 +0,0 @@
using JT808.DotNetty.Core;
using JT808.DotNetty.Core.Interfaces;
using JT808.Protocol;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using JT808.Protocol.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JT808.Protocol.MessageBody;
using JT808.DotNetty.Abstractions.Dtos;

namespace JT808.DotNetty.Tcp.Test
{
[TestClass]
public class JT808UnificationTcpSendServiceTest: TestBase
{
static IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6565);

private IJT808UnificationSendService jT808UnificationSendService;
private IJT808SessionService jT808SessionServiceDefaultImpl;

public JT808UnificationTcpSendServiceTest()
{
JT808SimpleTcpClient SimpleTcpClient1 = new JT808SimpleTcpClient(endPoint);
JT808SimpleTcpClient SimpleTcpClient2 = new JT808SimpleTcpClient(endPoint);
JT808SimpleTcpClient SimpleTcpClient3 = new JT808SimpleTcpClient(endPoint);
JT808SimpleTcpClient SimpleTcpClient4 = new JT808SimpleTcpClient(endPoint);
JT808SimpleTcpClient SimpleTcpClient5 = new JT808SimpleTcpClient(endPoint);
// 心跳会话包
JT808Package jT808Package1 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789001");
SimpleTcpClient1.WriteAsync(JT808Serializer.Serialize(jT808Package1));

// 心跳会话包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789002");
SimpleTcpClient2.WriteAsync(JT808Serializer.Serialize(jT808Package2));

// 心跳会话包
JT808Package jT808Package3 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789003");
SimpleTcpClient3.WriteAsync(JT808Serializer.Serialize(jT808Package3));

// 心跳会话包
JT808Package jT808Package4 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789004");
SimpleTcpClient4.WriteAsync(JT808Serializer.Serialize(jT808Package4));

// 心跳会话包
JT808Package jT808Package5 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789005");
SimpleTcpClient5.WriteAsync(JT808Serializer.Serialize(jT808Package5));

Thread.Sleep(300);
}

[TestMethod]
public void Test1()
{
jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
jT808UnificationSendService = ServiceProvider.GetService<IJT808UnificationSendService>();
jT808SessionServiceDefaultImpl.GetTcpAll();
string no = "123456789001";
// 文本信息包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.文本信息下发.Create(no, new JT808_0x8300
{
TextFlag = 5,
TextInfo = "smallchi 518"
});
var data = JT808Serializer.Serialize(jT808Package2);
JT808ResultDto<bool> jt808Result = jT808UnificationSendService.Send(no, data);
Thread.Sleep(1000);
Assert.AreEqual(200, jt808Result.Code);
Assert.IsTrue(jt808Result.Data);
}
}
}

+ 50
- 23
src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/TestBase.cs Ver arquivo

@@ -1,5 +1,13 @@
using JT808.DotNetty.Core;
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels.Embedded;
using JT808.DotNetty.Core;
using JT808.DotNetty.Core.Codecs;
using JT808.DotNetty.Core.Impls;
using JT808.DotNetty.Core.Metadata;
using JT808.DotNetty.Tcp.Handlers;
using JT808.Protocol;
using JT808.Protocol.Extensions;
using JT808.Protocol.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -13,30 +21,49 @@ namespace JT808.DotNetty.Tcp.Test
{
public class TestBase
{
public static IServiceProvider ServiceProvider;
public static JT808Serializer JT808Serializer;
static TestBase()
public IServiceProvider ServiceProvider;
public JT808Serializer JT808Serializer;
public TestBase()
{
var serverHostBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddJT808Configure()
.AddJT808NettyCore(hostContext.Configuration)
.AddJT808TcpNettyHost()
.Builder();
//.Replace<>;
});
var build = serverHostBuilder.Build();
build.Start();
ServiceProvider = build.Services;
IServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddSingleton<ILoggerFactory, LoggerFactory>();
serviceDescriptors.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
serviceDescriptors.AddJT808Configure()
.AddJT808NettyCore(options => { })
.Builder();
serviceDescriptors.AddJT808TcpNettyHostTest();
ServiceProvider = serviceDescriptors.BuildServiceProvider();
JT808Serializer = ServiceProvider.GetRequiredService<IJT808Config>().GetSerializer();
}

public EmbeddedChannel CreateEmbeddedChannel()
{
using (var soppe = ServiceProvider.CreateScope())
{
var handler1 = soppe.ServiceProvider.GetRequiredService<JT808TcpEncoder>();
var handler2 = soppe.ServiceProvider.GetRequiredService<JT808TcpDecoder>();
var handler3 = soppe.ServiceProvider.GetRequiredService<JT808TcpServerHandler>();
var ch = new EmbeddedChannel(new JT808DefaultChannelId(),
new DelimiterBasedFrameDecoder(int.MaxValue,Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.BeginFlag }),Unpooled.CopiedBuffer(new byte[] { JT808.Protocol.JT808Package.EndFlag })),
handler1,
handler2,
handler3);
return ch;
}
}

public Dictionary<string, EmbeddedChannel> Channels = new Dictionary<string, EmbeddedChannel>();

public void SeedSession(params string[] terminalPhoneNos)
{
foreach (var item in terminalPhoneNos)
{
JT808Package jT808Package = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create(item);
var tmp1=JT808Serializer.Serialize(jT808Package);
var ch = CreateEmbeddedChannel();
ch.WriteInbound(Unpooled.CopiedBuffer(tmp1));
Channels.Add(item, ch);
}
}
}
}

+ 0
- 21
src/JT808.DotNetty.Tests/JT808.DotNetty.Tcp.Test/appsettings.json Ver arquivo

@@ -1,21 +0,0 @@
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Trace"
}
},
"Console": {
"LogLevel": {
"Default": "Trace"
}
}
},
"JT808Configuration": {
"TcpPort": 6565,
"ForwardingRemoteIPAddress": [
"127.0.0.1"
]
}
}

+ 3
- 14
src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808.DotNetty.Udp.Test.csproj Ver arquivo

@@ -11,24 +11,13 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="MSTest.TestAdapter" Version="2.0.0" />
<PackageReference Include="MSTest.TestFramework" Version="2.0.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\JT808.DotNetty.Udp\JT808.DotNetty.Udp.csproj" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>

+ 61
- 59
src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808SessionServiceTest.cs Ver arquivo

@@ -8,86 +8,88 @@ using System.Text;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using JT808.Protocol.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JT808.DotNetty.Core.Session;
using JT808.DotNetty.Abstractions.Dtos;
using Xunit;
using DotNetty.Transport.Channels.Embedded;
using Microsoft.Extensions.Logging;
using JT808.DotNetty.Core.Codecs;
using JT808.DotNetty.Udp.Handlers;
using JT808.Protocol.MessageBody;
using System.Linq;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Buffers;

namespace JT808.DotNetty.Udp.Test
{
[TestClass]
public class JT808SessionServiceTest:TestBase,IDisposable
public class JT808SessionServiceTest:TestBase
{
static IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 818);
JT808SimpleUdpClient SimpleUdpClient1;
JT808SimpleUdpClient SimpleUdpClient2;
JT808SimpleUdpClient SimpleUdpClient3;
JT808SimpleUdpClient SimpleUdpClient4;
JT808SimpleUdpClient SimpleUdpClient5;

public void Dispose()
{
SimpleUdpClient1.Down();
SimpleUdpClient2.Down();
SimpleUdpClient3.Down();
SimpleUdpClient4.Down();
SimpleUdpClient5.Down();
}

List<string> TNos = new List<string> {
"123456789001",
"123456789002",
"123456789003",
"123456789004",
"123456789005"
};
public JT808SessionServiceTest()
{
SimpleUdpClient1 = new JT808SimpleUdpClient(endPoint);
SimpleUdpClient2 = new JT808SimpleUdpClient(endPoint);
SimpleUdpClient3 = new JT808SimpleUdpClient(endPoint);
SimpleUdpClient4 = new JT808SimpleUdpClient(endPoint);
SimpleUdpClient5 = new JT808SimpleUdpClient(endPoint);
// 心跳会话包
JT808Package jT808Package1 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789001");
SimpleUdpClient1.WriteAsync(JT808Serializer.Serialize(jT808Package1));

// 心跳会话包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789002");
SimpleUdpClient2.WriteAsync(JT808Serializer.Serialize(jT808Package2));

// 心跳会话包
JT808Package jT808Package3 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789003");
SimpleUdpClient3.WriteAsync(JT808Serializer.Serialize(jT808Package3));

// 心跳会话包
JT808Package jT808Package4 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789004");
SimpleUdpClient4.WriteAsync(JT808Serializer.Serialize(jT808Package4));

// 心跳会话包
JT808Package jT808Package5 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789005");
SimpleUdpClient5.WriteAsync(JT808Serializer.Serialize(jT808Package5));
Thread.Sleep(1000);
var ch1 = CreateEmbeddedChannel();
ch1.WriteInbound(JT808Serializer.Serialize(jT808Package1));
SeedSession(TNos.ToArray());
}

[TestMethod]
public void Test1()
[Fact]
public void GetUdpAllTest()
{
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
var result = jT808SessionServiceDefaultImpl.GetUdpAll();
var tons = result.Data.Select(s => s.TerminalPhoneNo).ToList();
foreach (var item in TNos)
{
Assert.Contains(item, tons);
}
Assert.Equal(JT808ResultCode.Ok, result.Code);
}

[TestMethod]
public void Test2()
[Fact]
public void RemoveByTerminalPhoneNoTest()
{
string tno = "123456789006";
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
var result1 = jT808SessionServiceDefaultImpl.GetUdpAll();
var result2 = jT808SessionServiceDefaultImpl.RemoveByTerminalPhoneNo("123456789001");
var result3 = jT808SessionServiceDefaultImpl.GetUdpAll();
SeedSession(tno);
var result1 = jT808SessionServiceDefaultImpl.RemoveByTerminalPhoneNo(tno);
Assert.Equal(JT808ResultCode.Ok, result1.Code);
Assert.True(result1.Data);
var result2 = jT808SessionServiceDefaultImpl.GetUdpAll();
Assert.Equal(JT808ResultCode.Ok, result2.Code);
Assert.DoesNotContain(tno, result2.Data.Select(s=>s.TerminalPhoneNo));
}

[TestMethod]
public void Test3()
[Fact]
public void SendTest()
{
// 判断通道是否关闭
IJT808SessionService jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
JT808SessionManager jT808UdpSessionManager = ServiceProvider.GetService<JT808SessionManager>();
var result1 = jT808SessionServiceDefaultImpl.GetUdpAll();
SimpleUdpClient1.Down();
var session = jT808UdpSessionManager.GetSessionByTerminalPhoneNo("123456789001");
var result3 = jT808UdpSessionManager.GetUdpAll();
Thread.Sleep(100000);
//"126 131 0 0 13 18 52 86 120 144 1 0 11 5 115 109 97 108 108 99 104 105 32 53 49 56 24 126"
var jT808UnificationSendService = ServiceProvider.GetService<IJT808UnificationSendService>();
string no = "123456789001";
// 文本信息包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.文本信息下发.Create(no, new JT808_0x8300
{
TextFlag = 5,
TextInfo = "smallchi 518"
});
var data = JT808Serializer.Serialize(jT808Package2);
JT808ResultDto<bool> jt808Result = jT808UnificationSendService.Send(no, data);
Assert.Equal(JT808ResultCode.Ok, jt808Result.Code);
Assert.True(jt808Result.Data);
if(Channels.TryGetValue(no,out var channel))
{
var package = channel.ReadOutbound<DatagramPacket>();
byte[] recevie = new byte[package.Content.Capacity];
package.Content.ReadBytes(recevie);
Assert.Equal(data, recevie);
}
}
}
}

+ 0
- 76
src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/JT808UnificationUdpSendServiceTest.cs Ver arquivo

@@ -1,76 +0,0 @@
using JT808.DotNetty.Core;
using JT808.DotNetty.Core.Interfaces;
using JT808.Protocol;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using JT808.Protocol.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using JT808.Protocol.MessageBody;
using JT808.DotNetty.Abstractions.Dtos;

namespace JT808.DotNetty.Udp.Test
{
[TestClass]
public class JT808UnificationUdpSendServiceTest : TestBase
{
static IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 818);

private IJT808UnificationSendService jT808UnificationSendService;
private IJT808SessionService jT808SessionServiceDefaultImpl;

public JT808UnificationUdpSendServiceTest()
{
JT808SimpleUdpClient SimpleUdpClient1 = new JT808SimpleUdpClient(endPoint);
JT808SimpleUdpClient SimpleUdpClient2 = new JT808SimpleUdpClient(endPoint);
JT808SimpleUdpClient SimpleUdpClient3 = new JT808SimpleUdpClient(endPoint);
JT808SimpleUdpClient SimpleUdpClient4 = new JT808SimpleUdpClient(endPoint);
JT808SimpleUdpClient SimpleUdpClient5 = new JT808SimpleUdpClient(endPoint);
// 心跳会话包
JT808Package jT808Package1 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789001");
SimpleUdpClient1.WriteAsync(JT808Serializer.Serialize(jT808Package1));

// 心跳会话包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789002");
SimpleUdpClient2.WriteAsync(JT808Serializer.Serialize(jT808Package2));

// 心跳会话包
JT808Package jT808Package3 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789003");
SimpleUdpClient3.WriteAsync(JT808Serializer.Serialize(jT808Package3));

// 心跳会话包
JT808Package jT808Package4 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789004");
SimpleUdpClient4.WriteAsync(JT808Serializer.Serialize(jT808Package4));

// 心跳会话包
JT808Package jT808Package5 = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create("123456789005");
SimpleUdpClient5.WriteAsync(JT808Serializer.Serialize(jT808Package5));

Thread.Sleep(300);
}

[TestMethod]
public void Test1()
{
//"126 131 0 0 13 18 52 86 120 144 1 0 11 5 115 109 97 108 108 99 104 105 32 53 49 56 24 126"
jT808SessionServiceDefaultImpl = ServiceProvider.GetService<IJT808SessionService>();
jT808UnificationSendService = ServiceProvider.GetService<IJT808UnificationSendService>();
jT808SessionServiceDefaultImpl.GetUdpAll();
string no = "123456789001";
// 文本信息包
JT808Package jT808Package2 = JT808.Protocol.Enums.JT808MsgId.文本信息下发.Create(no, new JT808_0x8300
{
TextFlag = 5,
TextInfo = "smallchi 518"
});
var data = JT808Serializer.Serialize(jT808Package2);
JT808ResultDto<bool> jt808Result = jT808UnificationSendService.Send(no, data);
Thread.Sleep(1000);
Assert.AreEqual(200, jt808Result.Code);
Assert.IsTrue(jt808Result.Data);
}
}
}

+ 47
- 20
src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/TestBase.cs Ver arquivo

@@ -8,33 +8,60 @@ using System.Collections.Generic;
using System.Text;
using JT808.Protocol;
using JT808.Protocol.Interfaces;
using DotNetty.Transport.Channels.Embedded;
using JT808.DotNetty.Core.Codecs;
using JT808.DotNetty.Udp.Handlers;
using JT808.Protocol.Extensions;
using DotNetty.Transport.Channels.Sockets;
using DotNetty.Buffers;
using System.Net;
using JT808.DotNetty.Core.Impls;

namespace JT808.DotNetty.Udp.Test
{
public class TestBase
{
public static IServiceProvider ServiceProvider;
public static JT808Serializer JT808Serializer;
static TestBase()
public IServiceProvider ServiceProvider;
public JT808Serializer JT808Serializer;
public TestBase()
{
var serverHostBuilder = new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddJT808Configure()
.AddJT808NettyCore(hostContext.Configuration)
.AddJT808UdpNettyHost();
});
var build = serverHostBuilder.Build();
build.Start();
ServiceProvider = build.Services;
IServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddSingleton<ILoggerFactory, LoggerFactory>();
serviceDescriptors.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
serviceDescriptors.AddJT808Configure()
.AddJT808NettyCore(options => { })
.Builder();
serviceDescriptors.AddJT808UdpNettyHostTest();
ServiceProvider = serviceDescriptors.BuildServiceProvider();
JT808Serializer = ServiceProvider.GetRequiredService<IJT808Config>().GetSerializer();
}

public EmbeddedChannel CreateEmbeddedChannel()
{
using (var soppe = ServiceProvider.CreateScope())
{
var handler1 = soppe.ServiceProvider.GetRequiredService<JT808UdpDecoder>();
var handler2 = soppe.ServiceProvider.GetRequiredService<JT808UdpServerHandler>();
var ch = new EmbeddedChannel(new JT808DefaultChannelId(),handler1, handler2);
return ch;
}
}

public Dictionary<string, EmbeddedChannel> Channels = new Dictionary<string, EmbeddedChannel>();

public void SeedSession(params string[] terminalPhoneNos)
{
foreach(var item in terminalPhoneNos)
{
JT808Package jT808Package = JT808.Protocol.Enums.JT808MsgId.终端心跳.Create(item);
var ch = CreateEmbeddedChannel();
DatagramPacket datagramPacket = new DatagramPacket(
Unpooled.CopiedBuffer(JT808Serializer.Serialize(jT808Package))
, new IPEndPoint(IPAddress.Any, 0)
, new IPEndPoint(IPAddress.Any, 0));
ch.WriteInbound(datagramPacket);
Channels.Add(item, ch);
}
}
}
}

+ 0
- 22
src/JT808.DotNetty.Tests/JT808.DotNetty.Udp.Test/appsettings.json Ver arquivo

@@ -1,22 +0,0 @@
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Trace"
}
},
"Console": {
"LogLevel": {
"Default": "Trace"
}
}
},
"JT808Configuration": {
"TcpPort": 6565,
"ForwardingRemoteIPAddress": [
"127.0.0.1"
],
"RedisHost": "127.0.0.1:6379"
}
}

+ 194
- 0
src/JT808.DotNetty.Tests/JT808.DotNetty.WebApi.Test/Handlers/JT808WebAPIServerHandlerTest.cs Ver arquivo

@@ -0,0 +1,194 @@
using DotNetty.Buffers;
using DotNetty.Codecs.Http;
using DotNetty.Common.Utilities;
using DotNetty.Transport.Channels.Embedded;
using JT808.DotNetty.Abstractions;
using JT808.DotNetty.Abstractions.Dtos;
using JT808.DotNetty.Abstractions.Enums;
using JT808.DotNetty.Core;
using JT808.DotNetty.Core.Handlers;
using JT808.DotNetty.Core.Interfaces;
using JT808.DotNetty.Core.Services;
using JT808.DotNetty.Core.Session;
using JT808.DotNetty.WebApi.Authorization;
using JT808.DotNetty.WebApi.Handlers;
using JT808.Protocol;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.Json;
using Xunit;
using HttpVersion = DotNetty.Codecs.Http.HttpVersion;

namespace JT808.DotNetty.WebApi.Test.Handlers
{
public class JT808WebAPIServerHandlerTest
{
[Fact]
public void SessionTcpGetAllTest()
{
var ch = WebExt.CreateEmbeddedChannel(serviceProvider => {
var sessionMgr = serviceProvider.GetRequiredService<JT808SessionManager>();
sessionMgr.TryAdd("12345678",new EmbeddedChannel());
});
ch.WriteInbound(WebExt.CreateGetRequest(JT808NettyConstants.JT808WebApiRouteTable.SessionTcpGetAll));
var result = ch.As<List<JT808TcpSessionInfoDto>>();
Assert.Single(result.Data);
Assert.Equal("12345678", result.Data[0].TerminalPhoneNo);
Assert.Equal(JT808ResultCode.Ok, result.Code);
}

[Fact]
public void GetUdpSessionAllTest()
{
var ch = WebExt.CreateEmbeddedChannel(serviceProvider => {
var sessionMgr=serviceProvider.GetRequiredService<JT808SessionManager>();
sessionMgr.TryAdd(new EmbeddedChannel(),new IPEndPoint(IPAddress.Parse("127.0.0.1"), 888),"123456789");
});
ch.WriteInbound(WebExt.CreateGetRequest(JT808NettyConstants.JT808WebApiRouteTable.SessionUdpGetAll));
var result = ch.As<List<JT808UdpSessionInfoDto>>();
Assert.Single(result.Data);
Assert.Equal("123456789",result.Data[0].TerminalPhoneNo);
Assert.Equal(JT808ResultCode.Ok, result.Code);
}

[Fact]
public void RemoveSessionByTerminalPhoneNoTest()
{
var ch = WebExt.CreateEmbeddedChannel();
ch.WriteInbound(WebExt.CreatePostRequest(JT808NettyConstants.JT808WebApiRouteTable.SessionRemoveByTerminalPhoneNo,Encoding.UTF8.GetBytes("12345678")));
var result = ch.As<bool>();
Assert.False(result.Data);
Assert.Equal(JT808ResultCode.Empty, result.Code);
Assert.Equal("Session Empty", result.Message);
}

[Fact]
public void UnificationSendTest()
{
var ch = WebExt.CreateEmbeddedChannel();
JT808UnificationSendRequestDto jT808UnificationSendRequestDto = new JT808UnificationSendRequestDto
{
TerminalPhoneNo = "123456789",
Data = new byte[] { 1, 2, 3, 4 }
};
byte[] content = JsonSerializer.SerializeToUtf8Bytes(jT808UnificationSendRequestDto);
ch.WriteInbound(WebExt.CreatePostRequest(JT808NettyConstants.JT808WebApiRouteTable.UnificationSend, content));
var result = ch.As<bool>();
Assert.False(result.Data);
Assert.Equal(JT808ResultCode.Ok, result.Code);
Assert.Equal("offline", result.Message);
}

[Fact]
public void GetTcpAtomicCounterTest()
{
var ch = WebExt.CreateEmbeddedChannel(serviceProvider=>
{
var counterFactory = serviceProvider.GetRequiredService<JT808AtomicCounterServiceFactory>();
var counter = counterFactory.Create(JT808TransportProtocolType.tcp);
counter.MsgSuccessIncrement();
counter.MsgSuccessIncrement();
counter.MsgFailIncrement();
});

ch.WriteInbound(WebExt.CreateGetRequest(JT808NettyConstants.JT808WebApiRouteTable.GetTcpAtomicCounter));
var result = ch.As<JT808AtomicCounterDto>();
Assert.Equal(2,result.Data.MsgSuccessCount);
Assert.Equal(1,result.Data.MsgFailCount);
Assert.Equal(JT808ResultCode.Ok, result.Code);
}

[Fact]
public void GetUdpAtomicCounterTest()
{
var ch = WebExt.CreateEmbeddedChannel(serviceProvider =>
{
var counterFactory = serviceProvider.GetRequiredService<JT808AtomicCounterServiceFactory>();
var counter = counterFactory.Create(JT808TransportProtocolType.udp);
counter.MsgSuccessIncrement();
counter.MsgSuccessIncrement();
counter.MsgSuccessIncrement();
counter.MsgFailIncrement();
});

ch.WriteInbound(WebExt.CreateGetRequest(JT808NettyConstants.JT808WebApiRouteTable.GetUdpAtomicCounter));
var result = ch.As<JT808AtomicCounterDto>();
Assert.Equal(3, result.Data.MsgSuccessCount);
Assert.Equal(1, result.Data.MsgFailCount);
Assert.Equal(JT808ResultCode.Ok, result.Code);
}
}

public static class WebExt
{
public static EmbeddedChannel CreateEmbeddedChannel()
{
IServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddSingleton<ILoggerFactory, LoggerFactory>();
serviceDescriptors.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
serviceDescriptors.AddJT808Configure()
.AddJT808NettyCore(options => { })
.Builder();
serviceDescriptors.AddJT808WebApiNettyHostTest();
var handler = serviceDescriptors.BuildServiceProvider().GetRequiredService<JT808WebAPIServerHandler>();
var ch = new EmbeddedChannel(
new HttpRequestDecoder(4096, 8192, 8192, false),
new HttpObjectAggregator(int.MaxValue),
handler);
return ch;
}

public static EmbeddedChannel CreateEmbeddedChannel(Action<IServiceProvider> action)
{
IServiceCollection serviceDescriptors = new ServiceCollection();
serviceDescriptors.AddSingleton<ILoggerFactory, LoggerFactory>();
serviceDescriptors.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
serviceDescriptors.AddJT808Configure()
.AddJT808NettyCore(options => { })
.Builder();
serviceDescriptors.AddSingleton<JT808MsgIdHttpHandlerBase, JT808MsgIdDefaultWebApiHandler>();
serviceDescriptors.AddSingleton<IJT808WebApiAuthorization, JT808AuthorizationDefault>();
serviceDescriptors.AddScoped<JT808WebAPIServerHandler>();
var serviceProvider = serviceDescriptors.BuildServiceProvider();
var handler = serviceProvider.GetRequiredService<JT808WebAPIServerHandler>();
var ch = new EmbeddedChannel(
new HttpRequestDecoder(4096, 8192, 8192, false),
new HttpObjectAggregator(int.MaxValue),
handler);
action(serviceProvider);
return ch;
}

public static JT808ResultDto<T> As<T>(this EmbeddedChannel embeddedChannel)
{
if(embeddedChannel == null) return default;
DefaultFullHttpResponse response = embeddedChannel.ReadOutbound<DefaultFullHttpResponse>();
if (response.Headers.TryGetInt(HttpHeaderNames.ContentLength, out int length))
{
byte[] tmp = new byte[length];
response.Content.ReadBytes(tmp);
response.Release();
return JsonSerializer.Deserialize<JT808ResultDto<T>>(tmp);
}
response.Release();
return default;
}
public static DefaultFullHttpRequest CreateGetRequest(string uri)
{
var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Get, uri);
request.Headers.Add((AsciiString)"token", "123456");
return request;
}
public static DefaultFullHttpRequest CreatePostRequest(string uri,byte[]content)
{
var request = new DefaultFullHttpRequest(HttpVersion.Http11, HttpMethod.Post, uri);
request.Headers.Add((AsciiString)"token", "123456");
request.Content.WriteBytes(content);
return request;
}
}
}

+ 1
- 1
src/JT808.DotNetty.Tests/JT808.DotNetty.WebApi.Test/JT808.DotNetty.WebApi.Test.csproj Ver arquivo

@@ -8,7 +8,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.2.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.3.0" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
<PackageReference Include="coverlet.collector" Version="1.0.1" />


+ 8
- 0
src/JT808.DotNetty.Udp/JT808UdpDotnettyExtensions.cs Ver arquivo

@@ -21,5 +21,13 @@ namespace JT808.DotNetty.Udp
jT808NettyBuilder.JT808Builder.Services.AddHostedService<JT808UdpServerHost>();
return jT808NettyBuilder;
}

internal static IServiceCollection AddJT808UdpNettyHostTest(this IServiceCollection serviceDescriptors)
{
serviceDescriptors.TryAddSingleton<IJT808DatagramPacket, JT808DatagramPacketImpl>();
serviceDescriptors.TryAddScoped<JT808UdpDecoder>();
serviceDescriptors.TryAddScoped<JT808UdpServerHandler>();
return serviceDescriptors;
}
}
}

+ 3
- 4
src/JT808.DotNetty.WebApi/Handlers/JT808MsgIdDefaultWebApiHandler.cs Ver arquivo

@@ -6,7 +6,7 @@ using JT808.DotNetty.Core.Interfaces;
using JT808.DotNetty.Core.Metadata;
using JT808.DotNetty.Core.Services;
using JT808.DotNetty.Internal;
using Newtonsoft.Json;
using System.Text.Json;

namespace JT808.DotNetty.WebApi.Handlers
{
@@ -120,7 +120,8 @@ namespace JT808.DotNetty.WebApi.Handlers
{
return EmptyHttpResponse();
}
JT808UnificationSendRequestDto jT808UnificationSendRequestDto = JsonConvert.DeserializeObject<JT808UnificationSendRequestDto>(request.Json);

JT808UnificationSendRequestDto jT808UnificationSendRequestDto = JsonSerializer.Deserialize<JT808UnificationSendRequestDto>(request.Json);
var result = jT808UnificationSendService.Send(jT808UnificationSendRequestDto.TerminalPhoneNo, jT808UnificationSendRequestDto.Data);
return CreateJT808HttpResponse(result);
}
@@ -135,8 +136,6 @@ namespace JT808.DotNetty.WebApi.Handlers
{
CreateRoute(JT808NettyConstants.JT808WebApiRouteTable.GetTcpAtomicCounter, GetTcpAtomicCounter);
CreateRoute(JT808NettyConstants.JT808WebApiRouteTable.SessionTcpGetAll, GetTcpSessionAll);

}

protected virtual void InitUdpRoute()


+ 8
- 5
src/JT808.DotNetty.WebApi/Handlers/JT808WebAPIServerHandler.cs Ver arquivo

@@ -49,13 +49,16 @@ namespace JT808.DotNetty.WebApi.Handlers
{
jT808HttpResponse = jT808MsgIdHttpHandlerBase.AuthFailHttpResponse();
}
if (jT808MsgIdHttpHandlerBase.HandlerDict.TryGetValue(msg.Uri,out var funcHandler))
{
jT808HttpResponse = funcHandler(new JT808HttpRequest(){ Json = msg.Content.ToString(Encoding.UTF8)});
}
else
{
jT808HttpResponse = jT808MsgIdHttpHandlerBase.NotFoundHttpResponse();
if (jT808MsgIdHttpHandlerBase.HandlerDict.TryGetValue(msg.Uri, out var funcHandler))
{
jT808HttpResponse = funcHandler(new JT808HttpRequest() { Json = msg.Content.ToString(Encoding.UTF8) });
}
else
{
jT808HttpResponse = jT808MsgIdHttpHandlerBase.NotFoundHttpResponse();
}
}
if (jT808HttpResponse != null)
{


+ 8
- 0
src/JT808.DotNetty.WebApi/JT808WebApiDotnettyExtensions.cs Ver arquivo

@@ -21,5 +21,13 @@ namespace JT808.DotNetty.WebApi
jT808NettyBuilder.JT808Builder.Services.AddHostedService<JT808WebAPIServerHost>();
return new JT808WebApiBuilderDefault(jT808NettyBuilder);
}

internal static IServiceCollection AddJT808WebApiNettyHostTest(this IServiceCollection serviceDescriptors)
{
serviceDescriptors.TryAddSingleton<JT808MsgIdHttpHandlerBase, JT808MsgIdDefaultWebApiHandler>();
serviceDescriptors.TryAddSingleton<IJT808WebApiAuthorization, JT808AuthorizationDefault>();
serviceDescriptors.TryAddScoped<JT808WebAPIServerHandler>();
return serviceDescriptors;
}
}
}

+ 1
- 1
src/Version.props Ver arquivo

@@ -1,5 +1,5 @@
<Project>
<PropertyGroup>
<JT808DotNettyPackageVersion>2.2.1</JT808DotNettyPackageVersion>
<JT808DotNettyPackageVersion>2.2.2-preview1</JT808DotNettyPackageVersion>
</PropertyGroup>
</Project>

Carregando…
Cancelar
Salvar