using System; using System.Collections.Generic; using System.Text; using TouchSocket.Core; using TouchSocket.Sockets; namespace SunlightAggregationTerminal.Class { public class TcpServer { public static string ServerIP = ""; public static string ServerName = ""; public static string ServerPassword = ""; public static string ServerTerminal = ""; public static TcpClient tcpClient = new TcpClient(); public static void Configuration(string ip, string Name, string Password, string Terminal) { ServerIP = ip; ServerName = Name; ServerPassword = Password; ServerTerminal = Terminal; } public static async void Query(string Dat) { //发送字符串数据 await tcpClient.SendAsync("hello"); } private static async Task CreateCustomService() { tcpClient.Config.SetRemoteIPHost(ServerIP); 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; };//从服务器断开连接,当连接不成功时不会触发。 #region Tcp客户端使用Received异步委托接收数据 tcpClient.Received = (client, e) => { //从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。 var mes = e.Memory.Span.ToString(Encoding.UTF8); tcpClient.Logger.Info($"客户端接收到信息:{mes}"); return EasyTask.CompletedTask; }; #endregion await tcpClient.ConnectAsync();//调用连接,当连接不成功时,会抛出异常。 } } }