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.

151 lines
4.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
using TcpClient = TouchSocket.Sockets.TcpClient;
namespace HighWayIot.TouchSocket
{
public class TouchSocketTcpClient
{
/// <summary>
/// 懒加载
/// </summary>
private static readonly Lazy<TouchSocketTcpClient> lazy = new Lazy<TouchSocketTcpClient>(() => new TouchSocketTcpClient());
public static TouchSocketTcpClient Instance => lazy.Value;
/// <summary>
/// 所有的客户端
/// </summary>
public Dictionary<string, TcpClient> Clients = new Dictionary<string, TcpClient>();
public int ClientsCount = 0;
public Action<byte[], string> GetMessageAction;
public bool CreateTcpClient(string ip, string port)
{
TcpClient tcpClient = new TcpClient();
tcpClient.Connecting = (client, e) =>
{
return EasyTask.CompletedTask;
};//有客户端正在连接
tcpClient.Connected = (client, e) =>
{
return EasyTask.CompletedTask;
};//有客户端成功连接
tcpClient.Closing = (client, e) =>
{
return EasyTask.CompletedTask;
};//有客户端正在断开连接,只有当主动断开时才有效。
tcpClient.Closed = (client, e) =>
{
return EasyTask.CompletedTask;
};//有客户端断开连接
tcpClient.Received = (client, e) =>
{
var mes = e.Memory.Span.ToString(Encoding.UTF8);
GetMessageAction.Invoke(e.Memory.Span.ToArray(), client.IP);
tcpClient.Logger.Info($"客户端接收到信息:{mes}");
return EasyTask.CompletedTask;
//GetMessageAction.Invoke(e.ByteBlock.Span.ToArray(), client.IP);
//return EasyTask.CompletedTask;
}; //接收信号
tcpClient.SetupAsync(new TouchSocketConfig()
.SetRemoteIPHost($"{ip}:{port}")
.ConfigureContainer(a =>
{
a.AddConsoleLogger();//添加一个日志注入
})
.ConfigurePlugins(a =>
{
a.UseReconnection<TcpClient>(options =>
{
options.PollingInterval = TimeSpan.FromSeconds(1);
});
})
);
Result result = Result.Default; //不断尝试重连
do
{
result = tcpClient.TryConnectAsync().GetAwaiter().GetResult();
Task.Delay(1000).Wait();
}
while (!result.IsSuccess);
if (Clients.ContainsKey(ip))
{
Clients.Remove(ip);
Clients.Add(ip, tcpClient);
}
else
{
Clients.Add(ip, tcpClient);
}
return true;
}
/// <summary>
/// 信息发送
/// </summary>
/// <param name="message">Bytes</param>
/// <returns></returns>
public bool Send(string ip, byte[] message)
{
try
{
if (Clients.ContainsKey(ip))
{
Clients[ip].SendAsync(message);
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
}
}
/// <summary>
/// 客户端释放
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public bool DisposeClient(string ip)
{
try
{
if (Clients.ContainsKey(ip))
{
Clients[ip].CloseAsync();
Clients[ip].Dispose();
Clients.Remove(ip);
}
else
{
return false;
}
return true;
}
catch (Exception e)
{
return false;
}
}
}
}