LaserRemoval.cs
10.7 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
using HHECS.BllModel;
using HHECS.Infrastructure.Enums;
using HHECS.Infrastructure.Notice;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading;
namespace HHECS.Executor.EquipmentHandler.Marking
{
/// <summary>
///
/// 激光除锈信号发送
/// </summary>
public class LaserRemoval
{
private static Dictionary<string, ServerConnection> servers = new Dictionary<string, ServerConnection>();
private static readonly object serversLock = new object();
private static bool isRunning = true;
public static BllResult ConnectToServer(string serverId, string host, int port)
{
// 检查是否已连接到该服务器
lock (serversLock)
{
if (servers.ContainsKey(serverId))
{
return BllResultFactory.Success($"已连接到服务器 {serverId}");
}
}
// 创建新的服务器连接
ServerConnection connection = new ServerConnection
{
ServerId = serverId,
Host = host,
Port = port,
LastHeartbeat = DateTime.Now
};
// 启动连接线程
Thread connectThread = new Thread(() => Connect(connection));
connectThread.IsBackground = true;
connectThread.Start();
return BllResultFactory.Success();
}
static void Connect(ServerConnection connection)
{
try
{
TcpClient client = new TcpClient();
client.Connect(connection.Host, connection.Port);
// 连接成功,更新连接信息
lock (serversLock)
{
connection.Client = client;
connection.Connected = true;
servers[connection.ServerId] = connection;
}
NoticeBus.Notice($"成功连接到服务器 {connection.ServerId}", Level.Info);
// 发送设备标识
//SendMessage(connection, new Message
//{
// Type = "IDENTIFY",
// DeviceId = "ClientDevice",
// Content = "Client Connected"
//});
// 启动接收线程
Thread receiveThread = new Thread(() => ReceiveMessages(connection));
receiveThread.IsBackground = true;
receiveThread.Start();
// 启动心跳线程
Thread heartbeatThread = new Thread(() => SendHeartbeats(connection));
heartbeatThread.IsBackground = true;
heartbeatThread.Start();
}
catch (Exception ex)
{
NoticeBus.Notice($"连接服务器 {connection.ServerId} 失败: {ex.Message}", Level.Error);
// 连接失败,尝试重连
Reconnect(connection);
}
}
public static void Reconnect(ServerConnection connection)
{
// 标记为未连接
lock (serversLock)
{
connection.Connected = false;
if (connection.Client != null)
{
try { connection.Client.Close(); } catch { }
connection.Client = null;
}
}
Thread.Sleep(5000);
// 重新连接
if (isRunning)
{
Thread connectThread = new Thread(() => Connect(connection));
connectThread.IsBackground = true;
connectThread.Start();
}
}
static void ReceiveMessages(ServerConnection connection)
{
NetworkStream stream = null;
byte[] buffer = new byte[1024];
try
{
while (isRunning && connection.Connected && connection.Client.Connected)
{
if (stream == null)
stream = connection.Client.GetStream();
if (!IsConnected(connection.Client))
break;
// 检查是否有数据可读
if (connection.Client.Available > 0)
{
int bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Message message = Message.Parse(data);
message.DeviceId = connection.ServerId;
message.Type = "COMMAND";
// 更新心跳时间
connection.LastHeartbeat = DateTime.Now;
// 处理不同类型的消息
switch (message.Type)
{
case "HEARTBEAT":
NoticeBus.Notice($"收到来自服务器 {connection.ServerId} 的心跳", Level.Error);
break;
case "COMMAND":
NoticeBus.Notice($"收到来自服务器 {connection.ServerId} 的命令: {message.Content}", Level.Info);
// 处理命令...
break;
default:
NoticeBus.Notice($"收到来自服务器 {connection.ServerId} 的未知类型消息: {message.Type}", Level.Error);
break;
}
}
}
else
{
Thread.Sleep(100);
}
}
}
catch (Exception ex)
{
NoticeBus.Notice($"从服务器 {connection.ServerId} 接收消息时出错: {ex.Message}", Level.Error);
}
finally
{
// 连接断开,尝试重连
if (isRunning)
{
Reconnect(connection);
}
}
}
static void SendHeartbeats(ServerConnection connection)
{
while (isRunning && connection.Connected)
{
try
{
//if (connection.Client != null && connection.Client.Connected)
//{
// SendMessage(connection, new Message
// {
// Type = "HEARTBEAT",
// DeviceId = "ClientDevice",
// Content = "Ping"
// });
//}
//else
//{
// break;
//}
}
catch (Exception ex)
{
NoticeBus.Notice($"向服务器 {connection.ServerId} 发送心跳时出错: {ex.Message}", Level.Error);
break;
}
// 每5秒发送一次心跳
Thread.Sleep(5000);
}
}
public static BllResult SendMessage(ServerConnection connection, Message message)
{
if (!connection.Connected || connection.Client == null || !connection.Client.Connected)
{
return BllResultFactory.Error(($"无法发送消息到服务器 {connection.ServerId}: 未连接"));
}
try
{
string json = message.ToJson();
byte[] data = Encoding.UTF8.GetBytes(json);
NetworkStream stream = connection.Client.GetStream();
stream.Write(data, 0, data.Length);
return BllResultFactory.Success();
}
catch (Exception ex)
{
Reconnect(connection);
return BllResultFactory.Error($"向服务器 {connection.ServerId} 发送消息时出错: {ex.Message}");
}
}
// 检查Socket连接是否仍然有效
public static bool IsConnected(TcpClient client)
{
if (client == null || !client.Connected)
return false;
Socket socket = client.Client;
return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
}
}
// 服务器连接信息类
public class ServerConnection
{
public string ServerId { get; set; }
public string Host { get; set; }
public int Port { get; set; }
public TcpClient Client { get; set; }
public bool Connected { get; set; }
public DateTime LastHeartbeat { get; set; }
}
// 消息类
public class Message
{
public string Type { get; set; }
public string DeviceId { get; set; }
public string Content { get; set; }
public string ToJson()
{
return $"{{\"type\":\"{Type}\",\"deviceId\":\"{DeviceId}\",\"content\":\"{Content}\"}}";
}
public static Message Parse(string json)
{
try
{
// 简单解析,实际应用中应使用JSON库
Message message = new Message();
// 提取type字段
int typeStart = json.IndexOf("\"type\":\"") + 8;
int typeEnd = json.IndexOf("\"", typeStart);
if (typeStart > 7 && typeEnd > typeStart)
message.Type = json.Substring(typeStart, typeEnd - typeStart);
// 提取deviceId字段
int deviceIdStart = json.IndexOf("\"deviceId\":\"") + 11;
int deviceIdEnd = json.IndexOf("\"", deviceIdStart);
if (deviceIdStart > 10 && deviceIdEnd > deviceIdStart)
message.DeviceId = json.Substring(deviceIdStart, deviceIdEnd - deviceIdStart);
// 提取content字段
int contentStart = json.IndexOf("\"content\":\"") + 11;
int contentEnd = json.LastIndexOf("\"");
if (contentStart > 10 && contentEnd > contentStart)
message.Content = json.Substring(contentStart, contentEnd - contentStart);
return message;
}
catch
{
return new Message { Type = "UNKNOWN", DeviceId = "UNKNOWN", Content = json };
}
}
}
}