gps 数据推送调整

This commit is contained in:
yanghongwei 2024-09-02 14:24:54 +08:00
parent b250b0a297
commit 101dc1fef6
3 changed files with 67 additions and 16 deletions

View File

@ -13,6 +13,14 @@ namespace langguanApi.Common.WebSocket
{
private readonly IHubContext<SocketHub> _hubContext;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="hubContext"></param>
public PushService(IHubContext<SocketHub> hubContext)
{
_hubContext = hubContext;
}
/// <summary>
/// 全部消息
/// </summary>
/// <param name="message"></param>
@ -23,7 +31,7 @@ namespace langguanApi.Common.WebSocket
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
Console.WriteLine($"gps:{JsonConvert.SerializeObject(message, settings)}");
Console.WriteLine($"gps 推送数据:{JsonConvert.SerializeObject(message, settings)}");
var data = JsonConvert.SerializeObject(message, settings);
await _hubContext.Clients.All.SendAsync("ReceiveMessage", data);
}

View File

@ -1,4 +1,5 @@
using langguanApi.Common.Redis;
using langguanApi.Common.WebSocket;
using langguanApi.Extensions;
using langguanApi.Extensions.AutoDI;
using langguanApi.Middleware;
@ -45,7 +46,8 @@ builder.Services.AddSwaggerGen(
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
//websocket
builder.Services.AddSignalR();
//redis
var redisoptions = builder.Configuration.GetSection("Redis").Get<RedisOptions>();
if (redisoptions != null)
@ -76,6 +78,13 @@ builder.Services.AddCors(options =>
var app = builder.Build();
ServiceLocator.Instance = app.Services;
app.UseRouting();
//执行匹配的端点
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<SocketHub>("/notification");
endpoints.MapControllers();
});
// Configure the HTTP request pipeline.
@ -90,9 +99,8 @@ app.UseCors("CorsPolicy");
//app.UseAuthorization();
app.MapControllers();
if (!await GetNowTimeAsync())
{
Console.WriteLine("当前时间不在可运行时间范围内,请联系供应商。");

View File

@ -1,15 +1,17 @@
using langguanApi.Model.Entity;
using MongoDB.Bson.IO;
using Org.BouncyCastle.Utilities.Net;
using System.Net;
using System.Net.Sockets;
using System.Text;
using IPAddress = System.Net.IPAddress;
namespace langguanApi.Service
{
public class GpsService
{
private GpsHistoryService _service = ServiceLocator.Instance.GetService<GpsHistoryService>();
/// <summary>
/// 缓冲器
/// </summary>
@ -22,17 +24,24 @@ namespace langguanApi.Service
public async Task Start()
{
// 创建本地IP地址和TCP端口号
var ipEndPoint = new IPEndPoint(IPAddress.Any, port);
TcpListener listener = new(ipEndPoint);
// 定义监听地址和端口
try
{
// 定义监听地址和端口
IPAddress ipAddress = IPAddress.Any; // 使用本地所有可用的 IP 地址
// 创建 TcpListener 实例
TcpListener listener = new TcpListener(ipAddress, port);
// 开始监听
listener.Start();
Console.WriteLine($"Waiting for gps connection... port:{port}");
using TcpClient handler = await listener.AcceptTcpClientAsync();
await using NetworkStream stream = handler.GetStream();
int received = await stream.ReadAsync(result);
var message = Encoding.UTF8.GetString(result, 0, received);
Console.WriteLine($"GPS received: \"{message}\"");
Console.WriteLine($" gps Listening on {ipAddress}:{port}...");
while (true)
{
// 接受客户端连接
TcpClient client = await listener.AcceptTcpClientAsync();
// 处理客户端连接
_ = Task.Run(() => HandleClientAsync(client));
}
}
catch (Exception ex)
{
@ -44,10 +53,36 @@ namespace langguanApi.Service
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task Send(string message)
public async Task HandleClientAsync(TcpClient client)
{
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<GpsHistoryDTO>(message);
await _service.AddGpsHistory(json);
string receivedData = string.Empty;
using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
// 持续读取数据直到客户端断开连接
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
// 将字节数据转换为字符串
receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine($" gps Received: {receivedData}");
var json = Newtonsoft.Json.JsonConvert.DeserializeObject<GpsHistoryDTO>(receivedData);
var _service = ServiceLocator.Instance.GetService<GpsHistoryService>();
await _service.AddGpsHistory(json);
// 发送响应给客户端
string response = "Data received";
byte[] responseData = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(responseData, 0, responseData.Length);
}
}
client.Close();
Console.WriteLine("Client disconnected.");
}
}
}