using HslCommunication;
|
using System;
|
using System.IO;
|
using System.Net.Sockets;
|
using System.Text;
|
|
namespace PLCHelper
|
{
|
public class RestTcpClient : IDisposable
|
{
|
public string IP { get; private set; }
|
public int Port { get; private set; }
|
|
public int ReceiveTimeout { get; set; } = 5000;
|
|
private TcpClient tcpClient;
|
private Stream Stream;
|
private BinaryReader reader;
|
private BinaryWriter writer;
|
|
public RestTcpClient(string ip, int port)
|
{
|
IP = ip;
|
Port = port;
|
}
|
|
public void ConnectServer()
|
{
|
tcpClient = new TcpClient(IP, Port);
|
tcpClient.ReceiveTimeout = ReceiveTimeout;
|
Stream = tcpClient.GetStream();
|
reader = new BinaryReader(Stream);
|
writer = new BinaryWriter(Stream);
|
}
|
|
public OperateResult<bool> ReadBool(string data)
|
{
|
OperateResult<bool> res = new OperateResult<bool>();
|
if (Request(data, out string response, out string errMsg))
|
{
|
res.Content = bool.Parse(response);
|
res.IsSuccess = true;
|
}
|
else
|
{
|
res.Message = errMsg;
|
res.IsSuccess = false;
|
}
|
return res;
|
}
|
|
public OperateResult Write(string data, bool val)
|
{
|
OperateResult res = new OperateResult();
|
if (Request(data, out string response, out string errMsg))
|
{
|
res.IsSuccess = true;
|
}
|
else
|
{
|
res.Message = errMsg;
|
res.IsSuccess = false;
|
}
|
return res;
|
}
|
|
public void Send(string data)
|
{
|
data = data + "\r";
|
writer.Write(Encoding.UTF8.GetBytes(data));
|
writer.Flush();
|
}
|
|
public bool Request(string data, out string response, out string errMsg)
|
{
|
lock (this)
|
{
|
errMsg = string.Empty;
|
response = string.Empty;
|
try
|
{
|
Send(data);
|
response = Receive();
|
return true;
|
}
|
catch (Exception ex)
|
{
|
errMsg = ex.Message;
|
return false;
|
}
|
}
|
}
|
|
private string Receive()
|
{
|
byte[] array = new byte[1024];
|
int num = tcpClient.Client.Receive(array);
|
if (num == 0)
|
{
|
throw new Exception("Closed");
|
}
|
var bytes = new byte[num];
|
Array.Copy(array, bytes, num);
|
string data = Encoding.UTF8.GetString(bytes);
|
if (data.EndsWith("\r")) data = data.Substring(0, data.Length - 1);
|
return data;
|
}
|
|
public void Dispose()
|
{
|
tcpClient.Close();
|
}
|
}
|
}
|