TcpClientCommunication.cs
2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using HHECS.BllModel;
using System.Net.Sockets;
using System.Text;
namespace HHECS.DAQClient.Communications
{
public class TcpClientCommunication : ICommunication
{
public int CommunicationId { get; set; }
public string IpAddress => _ipAddress;
protected TcpClient tcpClient = new();
protected string _ipAddress = null!;
protected int _port;
protected byte[] _data = new byte[1024 * 8];
protected TcpClientCommunication() { }
public TcpClientCommunication(int communicationId, string ip, int port) : this()
{
CommunicationId = communicationId;
_ipAddress = ip;
_port = port;
}
public BllResult ConnectClose()
{
try
{
tcpClient.Close();
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
public BllResult ConnectServer()
{
try
{
tcpClient = new TcpClient();
tcpClient.Connect(_ipAddress, _port);
Task.Run(async () =>
{
try
{
while (tcpClient.Connected)
{
var stream = tcpClient.GetStream();
var buffer = new byte[_data.Length];
stream.Read(buffer);
var bufferString = Encoding.Default.GetString(buffer).TrimEnd('\0');
if (!string.IsNullOrWhiteSpace(bufferString))
{
_data = buffer;
}
await Task.Delay(100);
}
}
catch (Exception) { }
});
return BllResultFactory.Success();
}
catch (Exception ex)
{
return BllResultFactory.Error(ex.Message);
}
}
public virtual BllResult Read(IEnumerable<DataItem> dataItems)
{
throw new NotImplementedException();
}
public BllResult Read(DataItem dataItem)
{
return Read([dataItem]);
}
public virtual BllResult Write(IEnumerable<DataItem> dataItems)
{
throw new NotImplementedException();
}
public BllResult Write(DataItem dataItem)
{
return Write([dataItem]);
}
}
}