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.

121 lines
3.2 KiB
C#

3 weeks ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using NewLife.Log;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace NDSD_Screwdriver.Tool
{
public class QingTcpClient2
{
private int eable = -1;
TcpClient tcpClient = new TcpClient();
private Timer timer1 = null;
public QingTcpClient2(string str = "192.168.5.212:4545")
{
tcpClient.Connecting = (client, e) => EasyTask.CompletedTask;//即将连接到服务器此时已经创建socket但是还未建立tcp
tcpClient.Connected = (client, e) => EasyTask.CompletedTask;//成功连接到服务器
tcpClient.Setup(new TouchSocketConfig()
.SetRemoteIPHost(str)
.ConfigureContainer(a =>
{
a.AddConsoleLogger();//添加一个日志注入
}));
tcpClient.Received = (client, e) =>
{
//从服务器收到信息。但是一般byteBlock和requestInfo会根据适配器呈现不同的值。
var mes = e.ByteBlock.Span.ToString(Encoding.ASCII);
var sb= Sub(mes);
switch (sb)
{
case "0002":
switch (eable)
{
case 1:
client.Send("00200043 \0");
break;
case 0:
client.Send("00200042 \0");
break;
}
eable = -1;
break;
case "0043":
client.Send("00300064001 0000000000\0");
break;
}
XTrace.WriteLine($"客户端接收到信息:{mes}");
return EasyTask.CompletedTask;
};
tcpClient.Connect();
timer1 = new Timer();
timer1.Enabled = true;
timer1.Elapsed += timer1_Tick;
timer1.Interval = 500; //设置时间间隔毫秒为单位单位Ms
timer1.Start();
}
private string Sub(string str)
{
string mes = "";
var length = str.TrimStart().Length;
if (length>= 9)
{
mes= str.Substring(5, 4);
}
if (mes == "0005" && length >= 24)
{
mes = str.Substring(21, 4);
}
return mes;
}
private void timer1_Tick(object sender, EventArgs e)
{
tcpClient.Send("00209999 \0");
}
public void Begin()
{
tcpClient.Send("00200001 \0");
}
public void Enable()
{
eable = 1;
}
public void Close()
{
eable = 0;
}
public void Satus()
{
tcpClient.Send("00300064001 0000000000\0");
}
}
}