You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
73 lines
3.1 KiB
73 lines
3.1 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using TouchSocket.Core;
|
|
using TouchSocket.Sockets;
|
|
|
|
namespace SunlightAggregationManager.UserClass
|
|
{
|
|
public class AsyncTcpClient
|
|
{
|
|
public static TouchSocket.Sockets.TcpClient tcpClient = new TouchSocket.Sockets.TcpClient();
|
|
public static async void Configuration(string ip, string Name, string user, string Password)
|
|
{
|
|
await TcpClient(tcpClient, "tcp://"+ip);
|
|
}
|
|
public static async Task TcpClient(TouchSocket.Sockets.TcpClient tcpClient, string ip)
|
|
{
|
|
tcpClient.Connecting = (client, e) => { return EasyTask.CompletedTask; };//即将连接到服务器,此时已经创建socket,但是还未建立tcp
|
|
tcpClient.Connected = (client, e) =>
|
|
{
|
|
System.Data.DataRow targetRow =ViewModel.MainWindowViewModel._service.Select("ID = 1").FirstOrDefault()!;
|
|
if (targetRow != null)
|
|
{
|
|
targetRow.BeginEdit();
|
|
targetRow["Status"] = "Connected";
|
|
targetRow.EndEdit();
|
|
}
|
|
return EasyTask.CompletedTask;
|
|
};//成功连接到服务器
|
|
tcpClient.Closing = (client, e) => { return EasyTask.CompletedTask; };//即将从服务器断开连接。此处仅主动断开才有效。
|
|
tcpClient.Closed = (client, e) => {
|
|
System.Data.DataRow targetRow = ViewModel.MainWindowViewModel._service.Select("ID = 1").FirstOrDefault()!;
|
|
if (targetRow != null)
|
|
{
|
|
targetRow.BeginEdit();
|
|
targetRow["Status"] = "Disconnect";
|
|
targetRow.EndEdit();
|
|
}
|
|
return EasyTask.CompletedTask; };//从服务器断开连接,当连接不成功时不会触发。
|
|
#region Tcp客户端使用Received异步委托接收数据
|
|
tcpClient.Received = (client, e) =>
|
|
{
|
|
//从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
|
|
var mes = e.Memory.Span.ToString(Encoding.UTF8);
|
|
|
|
//DataReceived.Received(mes);
|
|
|
|
return EasyTask.CompletedTask;
|
|
};
|
|
#endregion
|
|
|
|
try
|
|
{
|
|
await tcpClient.SetupAsync(new TouchSocketConfig()
|
|
.SetSingleStreamDataHandlingAdapter(() => new PeriodPackageAdapter())//以超时周期和包
|
|
.SetRemoteIPHost(ip)
|
|
.ConfigurePlugins(a =>
|
|
{
|
|
a.UseReconnection<TouchSocket.Sockets.TcpClient>(options =>
|
|
{
|
|
options.PollingInterval = TimeSpan.FromSeconds(5);
|
|
});
|
|
}));
|
|
|
|
await tcpClient.ConnectAsync();//调用连接,当连接不成功时,会抛出异常。
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("Tcp:" + ex.ToString());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|