Files
T-DAS/Common/ModbusLightHelper.cs
2023-01-13 15:30:20 +08:00

132 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Epost.Common
{
public class ModbusLightHelper
{
public Socket newclient;
private IPEndPoint ie;
public bool Connect(string ipadd, int port)
{
byte[] data = new byte[1024];
//创建一个套接字
ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//将套接字与远程服务器地址相连
try
{
newclient.Connect(ie);
return true;
}
catch (SocketException e)
{
LogHelper.WriteLogInfo("通道灯异常"+e.Message);
return false;
}
}
public void LightLight(byte[] data)
{
while (true)
{
try
{
System.Threading.Thread.Sleep(150);
if (!newclient.Connected)
{
newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newclient.Connect(ie);
}
newclient.Send(data);
//while (true)//定义循环以便可以简历N次连接
//{
// LogHelper.WriteLogInfo("--start--");
// Thread.Sleep(2000);
// string recvStr = "";
// byte[] recvBytes = new byte[1024];
// int bytes;
// bytes = newclient.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
// recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
// string sendStr = "HTTP/1.0 200 OK";
// byte[] bs = Encoding.ASCII.GetBytes(sendStr);
// //newclient.Send(bs, bs.Length, 0);//返回信息给客户端
// if (newclient != null)
// newclient.Close();
// break;
//}
while (true)//定义一个循环接收返回数据
{
byte[] data1 = new byte[1024];
newclient.Receive(data1);
//int length = data1[5];
bool result = true;
for (var i = 0; i < 7; i++)
{
if (data[i] != data1[i])
result = false;
}
if (result)//(!string.IsNullOrWhiteSpace(stringData))
{
if (newclient != null)
newclient.Close();
break;
}
}
}
catch
{
continue;
}
break;
}
}
public void CloseSock()
{
if (newclient == null)
return;
if (!newclient.Connected)
return;
try
{
newclient.Shutdown(SocketShutdown.Both);
}
catch
{
}
try
{
newclient.Close();
}
catch
{
}
}
}
}