|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using System;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using TouchSocket.Core;
|
|
|
|
|
using TouchSocket.Sockets;
|
|
|
|
|
|
|
|
|
|
namespace SlnMesnac.TouchSocket
|
|
|
|
|
{
|
|
|
|
|
public class TcpServer
|
|
|
|
|
{
|
|
|
|
|
private ILogger<TcpServer> _logger;
|
|
|
|
|
private readonly TcpService _service;
|
|
|
|
|
|
|
|
|
|
public TcpServer(ILogger<TcpServer> logger,TcpService tcpService)
|
|
|
|
|
{
|
|
|
|
|
_logger = logger;
|
|
|
|
|
_service = tcpService;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Init(int serverPort)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
_service.Connecting = (client, e) => { //有客户端正在连接
|
|
|
|
|
_logger.LogInformation($"客户端{client.IP}正在接入服务");
|
|
|
|
|
};
|
|
|
|
|
_service.Connected = (client, e) => { //有客户端成功连接
|
|
|
|
|
_logger.LogInformation($"客户端{client.IP}接入服务成功,Id:{client.ID}");
|
|
|
|
|
};
|
|
|
|
|
_service.Disconnected = (client, e) => { //有客户端断开连接
|
|
|
|
|
_logger.LogInformation($"客户端{client.IP}断开连接,Id:{client.ID}");
|
|
|
|
|
};
|
|
|
|
|
_service.Received = (client, byteBlock, requestInfo) =>
|
|
|
|
|
{
|
|
|
|
|
//if (requestInfo is MyFixedHeaderRequestInfo myRequestInfo)
|
|
|
|
|
//{
|
|
|
|
|
// string body = Encoding.UTF8.GetString(myRequestInfo.Body, 0, myRequestInfo.Body.Length);
|
|
|
|
|
//}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
_service.Setup(new TouchSocketConfig()//载入配置
|
|
|
|
|
.SetListenIPHosts(new IPHost[] { new IPHost($"0.0.0.0:{serverPort}") })
|
|
|
|
|
//.SetDataHandlingAdapter(() => { return new MyFixedHeaderCustomDataHandlingAdapter(); })//配置适配器
|
|
|
|
|
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
|
|
|
|
|
{
|
|
|
|
|
a.AddConsoleLogger();//添加一个控制台日志注入(注意:在maui中控制台日志不可用)
|
|
|
|
|
})
|
|
|
|
|
.ConfigurePlugins(a =>
|
|
|
|
|
{
|
|
|
|
|
//a.Add<CheckClearPlugin>().SetDuration(new TimeSpan(0, 0, 0, 5, 0));
|
|
|
|
|
}))
|
|
|
|
|
.Start();//启动
|
|
|
|
|
_logger.LogInformation($"TcpServer启动成功,监听端口:{serverPort}");
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.LogError($"采集服务启动异常:{ex}");
|
|
|
|
|
throw new Exception(ex.Message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|