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.

140 lines
3.8 KiB
C#

2 months ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
2 months ago
using System.Threading;
2 months ago
using System.Threading.Tasks;
using NewLife.Log;
using TouchSocket.Core;
using TouchSocket.Sockets;
2 months ago
using Timer = System.Timers.Timer;
2 months ago
namespace NDSD_Screwdriver.Tool
{
public class QingTcpClient2
{
2 months ago
public int IsOk { get; set; }
public string updateTime { get; set; }
2 months ago
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);
2 months ago
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;
//
// case "0065":
// IsOk = mes.Substring(96, 19).ToInt();
// updateTime = mes.Substring(95, 1);
// break;
// }
// XTrace.WriteLine($"客户端接收到信息:{mes}");
2 months ago
return EasyTask.CompletedTask;
};
tcpClient.Connect();
2 months ago
Begin();
Thread.Sleep(200);
Satus();
2 months ago
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;
2 months ago
if (length >= 9)
2 months ago
{
2 months ago
mes = str.Substring(4, 4);
2 months ago
}
2 months ago
if (mes == "0005" && length >= 24)
2 months ago
{
2 months ago
mes = str.Substring(20, 4);
2 months ago
}
return mes;
}
private void timer1_Tick(object sender, EventArgs e)
{
2 months ago
2 months ago
tcpClient.Send("00209999 \0");
}
public void Begin()
{
2 months ago
2 months ago
tcpClient.Send("00200001 \0");
}
public void Enable()
{
2 months ago
// XTrace.WriteLine("枪发送使能");
2 months ago
tcpClient.Send("00200043 \0");
2 months ago
}
public void Close()
{
2 months ago
// XTrace.WriteLine("枪发送关闭");
2 months ago
tcpClient.Send("00200042 \0");
2 months ago
}
public void Satus()
{
2 months ago
2 months ago
tcpClient.Send("00300064001 0000000000\0");
}
}
}