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

191 lines
7.1 KiB
C#

2 months ago
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
2 months ago
using System.Linq;
2 months ago
using System.Text;
2 months ago
using Newtonsoft.Json.Linq;
2 months ago
using SlnMesnac.Model.domain;
2 months ago
using SlnMesnac.Repository.service;
2 months ago
using SlnMesnac.Repository.service.ScanLog;
2 months ago
using TouchSocket.Core;
using TouchSocket.Sockets;
2 months ago
2 months ago
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2024 WenJY
* CLR4.0.30319.42000
* LAPTOP-E0N2L34V
* SlnMesnac.TouchSocket
* 496f8d2b-70e3-4a05-ae18-a9b0fcd06b82
*
* WenJY
* wenjy@mesnac.com
* 2024-03-27 21:58:35
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.TouchSocket
{
2 months ago
public class TcpServer
{
private ILogger<TcpServer> _logger;
private readonly TcpService _service;
2 months ago
private readonly IScanLogService _scanService;
2 months ago
private readonly IBaseCodeService _baseCodeService;
// /// <summary>
// /// 接收客户端指令委托
// /// </summary>
// public delegate void ReceivedClientBuffer(byte[] buffer);
// public event ReceivedClientBuffer? ReceivedClientBufferEvent;
//
// public delegate void RefreshClientInfo(TcpService tcpService);
// public event RefreshClientInfo? RefreshClientInfoEvent;
2 months ago
2 months ago
public Action<ScanLogSocket>? ScanLogSocketAction;
public Action<ScanStatusSocket>? ScanStatusSocketAction;
2 months ago
2 months ago
public TcpServer(ILogger<TcpServer> logger,TcpService tcpService, IScanLogService scan, IBaseCodeService baseCodeService)
2 months ago
{
_logger = logger;
_service = tcpService;
2 months ago
_scanService = scan;
2 months ago
_baseCodeService = baseCodeService;
2 months ago
}
public void Init(int serverPort)
{
try
{
_service.Connecting = (client, e) => {
2 months ago
_logger.LogInformation("客户端{ClientIp}正在接入服务", client.IP);
2 months ago
return EasyTask.CompletedTask;
};
_service.Connected = (client, e) => {
2 months ago
_logger.LogInformation("客户端{ClientIp}接入服务成功", client.IP);
// RefreshClientInfoEvent?.Invoke(_service);
2 months ago
return EasyTask.CompletedTask;
};
_service.Disconnected = (client, e) => {
2 months ago
_logger.LogInformation("客户端{ClientIp}断开连接", client.IP);
// RefreshClientInfoEvent?.Invoke(_service);
2 months ago
return EasyTask.CompletedTask;
};
_service.Received = (client, e) =>
{
2 months ago
try
{
2 months ago
var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意数据长度是byteBlock.Len
_logger.LogInformation("收到数据:{Data}",mes);
// byte[] receivedBuffer = new byte[e.ByteBlock.Len];
// Array.Copy(e.ByteBlock.Buffer, 0, receivedBuffer, 0, e.ByteBlock.Len);
// ReceivedClientBufferEvent?.Invoke(receivedBuffer);
2 months ago
int dataType = 0;
var jObject = JObject.Parse(mes);
if (jObject.TryGetValue("data_type", out var value))
{
dataType=value.Value<int>();
}
if (dataType == 1)
{
2 months ago
2 months ago
ScanLogSocket scanStatus= mes.FromJsonString<ScanLogSocket>();
ScanLogSocketAction?.Invoke(scanStatus);
2 months ago
_scanService.Insert(new ScanLogModel()
{
CreateTime = scanStatus.CreateTime,
DataType = scanStatus.data_type,
Code = scanStatus.code,
Rfid = scanStatus.rfid,
Ocr = scanStatus.ocr,
Url = scanStatus.url
2 months ago
2 months ago
});
2 months ago
}
else
{
if (dataType == 2)
{
2 months ago
ScanStatusSocket scanStatus = mes.FromJsonString<ScanStatusSocket>();
ScanStatusSocketAction?.Invoke(scanStatus);
2 months ago
if (scanStatus.is_alarm == 1 && scanStatus.device_status != null && scanStatus.device_status.Count > 0)
2 months ago
{
List<string> ls = new List<string>();
2 months ago
var baseCodes = _baseCodeService.QuListCache();
2 months ago
foreach (var baseCode in scanStatus.device_status)
{
var enBaseCode = baseCodes.FirstOrDefault(x=>x.Code==baseCode);
if (enBaseCode != null)
{
ls.Add(enBaseCode.State);
}
}
scanStatus.status_txt = ls;
}
2 months ago
}
}
2 months ago
client.SendAsync(new Back().ToJsonString());
2 months ago
}
catch (Exception exception)
{
_logger.LogError(exception,exception.Message);
}
2 months ago
return EasyTask.CompletedTask;
};
_service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost($"0.0.0.0:{serverPort}") })
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
//自定义插件
}));
_service.Start();
_logger.LogInformation($"TcpServer启动成功监听端口{serverPort}");
}
catch (Exception ex)
{
//throw new InvalidOperationException($"TcpServer启动异常{ex.Message}");
_logger.LogError($"TcpServer启动异常{ex.Message}");
}
}
/// <summary>
/// 向所有客户端发送心跳
/// </summary>
public void SendHeartBeat()
{
var clients = _service.SocketClients.GetClients();
foreach (var item in clients)
{
_service.Send(item.Id,"heartbeat");
}
}
}
}