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.

182 lines
5.6 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using HighWayIot.Log4net;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace HighWayIot.TouchSocket
{
public class TcpClientServer
{
private static readonly Lazy<TcpClientServer> lazy = new Lazy<TcpClientServer>(() => new TcpClientServer());
public static TcpClientServer Instance => lazy.Value;
private static LogHelper logHelper = LogHelper.Instance;
TcpClient tcpClient = new TcpClient();
/// <summary>
/// 字符串数组转换为int数组
/// </summary>
public Action<string[]> GetBinCode;
public Action<string> GetString;
/// <summary>
/// 客户端状态获取
/// </summary>
public bool ClientState
{
get => tcpClient.Online;
}
/// <summary>
/// 客户端连接
/// </summary>
/// <returns></returns>
public async Task<bool> ClientConnect(string ip, string port)
{
try
{
if (!string.IsNullOrEmpty(tcpClient.IP))
{
tcpClient.Connect();
tcpClient.Logger.Info("客户端成功连接");
return true;
}
tcpClient.Connecting = (client, e) =>
{
return EasyTask.CompletedTask;
};//即将连接到服务器此时已经创建socket但是还未建立tcp
tcpClient.Connected = (client, e) =>
{
return EasyTask.CompletedTask;
};//成功连接到服务器
tcpClient.Closing = (client, e) =>
{
return EasyTask.CompletedTask;
};//即将从服务器断开连接。此处仅主动断开才有效。
tcpClient.Closed = (client, e) =>
{
return EasyTask.CompletedTask;
};//从服务器断开连接,当连接不成功时不会触发。
tcpClient.Received = async (client, e) =>
{
//从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
logHelper.Info($"客户端接收到信息:{mes}");
if (await MessageAnalyzer(mes))
{
logHelper.Info("数据解析成功");
}
else
{
logHelper.Error("数据解析失败或者getinfo信号发送失败");
}
};
//载入配置
await tcpClient.SetupAsync(new TouchSocketConfig()
.SetRemoteIPHost($"{ip}:{port}")
.ConfigureContainer(a =>
{
a.AddConsoleLogger();//添加一个日志注入
}));
tcpClient.Connect();//调用连接,当连接不成功时,会抛出异常。
tcpClient.Logger.Info("客户端成功连接");
return true;
}
catch (Exception ex)
{
tcpClient.Logger.Info("客户端连接失败" + ex);
return false;
}
}
/// <summary>
/// 接收数据分析
/// </summary>
/// <param name="mes"></param>
/// <returns></returns>
public async Task<bool> MessageAnalyzer(string mes)
{
try
{
if (mes.Contains("OK"))
{
await Send("getinfo");
}
else
{
//string[] binNoList = ClientStringAnalysis.GetInfoAnalyzer(mes);
GetString.Invoke(mes);
}
return true;
}
catch (ClientNotConnectedException ex)
{
logHelper.Error("发送数据发生错误" + ex);
return false;
}
catch (OverlengthException ex)
{
logHelper.Error("发送数据发生错误" + ex);
return false;
}
catch(Exception ex)
{
logHelper.Error("数据解析类发生错误" + ex);
return false;
}
}
/// <summary>
/// 信息发送
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public async Task<bool> Send(string message)
{
try
{
await tcpClient.SendAsync(message);
return true;
}
catch (Exception e)
{
logHelper.Error("发送数据发生错误" + e);
return false;
}
}
/// <summary>
/// 客户端关闭
/// </summary>
/// <returns></returns>
public async Task<bool> ClientClose()
{
try
{
await tcpClient.CloseAsync();
return true;
}
catch(Exception e)
{
logHelper.Error("关闭客户端发生错误" + e);
return false;
}
}
}
}