forked from wenjy/HighWayIot
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.
84 lines
2.5 KiB
C#
84 lines
2.5 KiB
C#
using HighWayIot.Log4net;
|
|
using System;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using TouchSocket.Core;
|
|
using TouchSocket.Sockets;
|
|
using TcpClient = TouchSocket.Sockets.TcpClient;
|
|
|
|
namespace HighWayIot.TouchSocket
|
|
{
|
|
public class TouchSocketTcpClient
|
|
{
|
|
private static LogHelper _logHelper = LogHelper.Instance;
|
|
|
|
private static readonly Lazy<TouchSocketTcpClient> lazy = new Lazy<TouchSocketTcpClient>(() => new TouchSocketTcpClient());
|
|
|
|
public static TouchSocketTcpClient Instance => lazy.Value;
|
|
|
|
TcpClient client = new TcpClient();
|
|
|
|
public async void TcpClient(string ip, string port)
|
|
{
|
|
client.Connecting = (client, e) =>
|
|
{
|
|
return EasyTask.CompletedTask;
|
|
};//有客户端正在连接
|
|
client.Connected = (client, e) =>
|
|
{
|
|
return EasyTask.CompletedTask;
|
|
};//有客户端成功连接
|
|
client.Closing = (client, e) =>
|
|
{
|
|
return EasyTask.CompletedTask;
|
|
};//有客户端正在断开连接,只有当主动断开时才有效。
|
|
client.Closed = (client, e) =>
|
|
{
|
|
return EasyTask.CompletedTask;
|
|
};//有客户端断开连接
|
|
client.Received = async (client, e) =>
|
|
{
|
|
//从客户端收到信息
|
|
var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
|
|
client.Logger.Info($"已从{client.IP}接收到信息:{mes}");
|
|
};
|
|
|
|
await client.SetupAsync(new TouchSocketConfig()
|
|
.SetRemoteIPHost($"{ip}:{port}")
|
|
.ConfigureContainer(a =>
|
|
{
|
|
a.AddConsoleLogger();//添加一个日志注入
|
|
}));
|
|
|
|
Result result = Result.Default; //不断尝试重连
|
|
do
|
|
{
|
|
result = await client.TryConnectAsync();
|
|
}
|
|
while (!result.IsSuccess);
|
|
|
|
return;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 信息发送
|
|
/// </summary>
|
|
/// <param name="message">Bytes</param>
|
|
/// <returns></returns>
|
|
public async Task<bool> Send(byte[] message)
|
|
{
|
|
try
|
|
{
|
|
await client.SendAsync(message);
|
|
return true;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
_logHelper.Error("发送数据发生错误" + e);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|