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.

126 lines
4.6 KiB
C#

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace SlnMesnac.TouchSocket
{
public class TcpServer
{
private ILogger<TcpServer> _logger;
private readonly TcpService _service;
#region 委托事件
/// <summary>
/// 刷新扫码器状态
/// </summary>
/// <param name="materialCodeStr"></param>
/// <param name="ip"></param>
public delegate void RefreshState(string ip, bool flag);
public static event RefreshState RefreshStateEvent;
//NoRead事件通知
//public delegate void MessageNoRead();
//public static event MessageNoRead MessageNoReadEvent;
//扫码事件
public delegate void RefreshMaterialCodeStr(string materialCodeStr, string ip);
public static event RefreshMaterialCodeStr RefreshMaterialCodeStrEvent;
#endregion
public TcpServer(ILogger<TcpServer> logger,TcpService tcpService)
{
_logger = logger;
_service = tcpService;
}
public void Init(int serverPort)
{
try
{
Console.WriteLine("启动Socket服务");
_service.Connecting = (client, e) => {
_logger.LogInformation($"客户端{client.IP}正在接入服务");
return EasyTask.CompletedTask;
};
_service.Connected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}接入服务成功");
RefreshStateEvent?.Invoke(client.IP, true);
return EasyTask.CompletedTask;
};
_service.Disconnected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}断开连接");
RefreshStateEvent?.Invoke(client.IP, false);
return EasyTask.CompletedTask;
};
_service.Received = (client, e) =>
{
try
{
//从客户端收到信息
var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意数据长度是byteBlock.Len
//心跳包
if (mes == "heartbeat")
{
//扫码器心跳连接
client.Logger.Info($"心跳{client.IP}:{client.Port}》接收到心跳信息:{mes}");
RefreshStateEvent?.Invoke(client.IP, true);
}
else if (mes == "NoRead")
{
client.Logger.Info($"入库扫码器{client.IP}:{client.Port}》NoRead事件{mes}");
}
else
{
client.Logger.Info($"入库扫码器{client.IP}:{client.Port}》接收到信息:{mes}");
RefreshMaterialCodeStrEvent?.Invoke(mes.Trim().TrimEnd('\0'), client.IP);
}
}
catch (Exception ex)
{
_logger.LogError($"socket接收数据异常:{ex.Message}");
}
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");
}
}
}
}