2 changed files with 83 additions and 0 deletions
@ -0,0 +1,82 @@ |
|||
using SunlightCentralizedControlManagement_SCCM_.UserClass; |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Data; |
|||
using System.Linq; |
|||
using System.Net; |
|||
using System.Net.Http; |
|||
using System.Net.Sockets; |
|||
using System.Reflection.Emit; |
|||
using System.Text; |
|||
using System.Threading; |
|||
using System.Threading.Tasks; |
|||
using System.Diagnostics; |
|||
using TouchSocket.Core; |
|||
using TouchSocket.Sockets; |
|||
using SunlightCentralizedControlManagement_SCCM_.ViewModel; |
|||
using System.Runtime.InteropServices; |
|||
using ScottPlot.Colormaps; |
|||
using static System.Windows.Forms.AxHost; |
|||
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock; |
|||
using static System.Windows.Forms.VisualStyles.VisualStyleElement; |
|||
using Newtonsoft.Json; |
|||
using static SunlightCentralizedControlManagement_SCCM_.UserClass.SqliteHelper; |
|||
using SunlightCentralizedControlManagement_SCCM_.View; |
|||
using TcpClient = TouchSocket.Sockets.TcpClient; |
|||
|
|||
namespace SunlightCentralizedControlManagement_SCCM_.UserClass |
|||
{/// <summary>
|
|||
/// 异步TCP客户端
|
|||
/// </summary>
|
|||
public class AsyncTcpClient |
|||
{ |
|||
public async Task TcpClient(string ip,string port) |
|||
{ |
|||
TcpClient tcpClient = new TcpClient(); |
|||
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 = (client, e) => |
|||
{ |
|||
//从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
|
|||
var mes = e.ByteBlock.Span.ToString(Encoding.UTF8); |
|||
tcpClient.Logger.Info($"客户端接收到信息:{mes}"); |
|||
return EasyTask.CompletedTask; |
|||
|
|||
}; |
|||
|
|||
//载入配置
|
|||
await tcpClient.SetupAsync(new TouchSocketConfig() |
|||
.SetRemoteIPHost(ip+":"+port) |
|||
.ConfigureContainer(a => |
|||
{ |
|||
a.AddConsoleLogger();//添加一个日志注入
|
|||
})); |
|||
|
|||
await tcpClient.ConnectAsync();//调用连接,当连接不成功时,会抛出异常。
|
|||
|
|||
Result result = await tcpClient.TryConnectAsync();//或者可以调用TryConnectAsync
|
|||
if (result.IsSuccess()) |
|||
{ |
|||
|
|||
} |
|||
|
|||
tcpClient.Logger.Info("客户端成功连接"); |
|||
} |
|||
|
|||
|
|||
// public Task SendAsync(string id, ReadOnlyMemory<byte> memory);
|
|||
// public Task SendAsync(string id, IRequestInfo requestInfo);
|
|||
|
|||
} |
|||
|
|||
|
|||
|
|||
} |
|||
|
|||
|
|||
|
|||
|
|||
|
|||
|
Loading…
Reference in new issue