-
Notifications
You must be signed in to change notification settings - Fork 3
/
PluginsServer.cs
290 lines (212 loc) · 7.38 KB
/
PluginsServer.cs
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
using Common.BasicHelper.Utils.Extensions;
using KitX_Dashboard.Data;
using KitX_Dashboard.Interfaces.Network;
using KitX_Dashboard.Managers;
using KitX_Dashboard.Services;
using Serilog;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace KitX_Dashboard.Network;
internal class PluginsServer : IKitXServer<PluginsServer>
{
private static TcpListener? listener = null;
private static bool keepListen = true;
private static bool disposed = false;
private static readonly Dictionary<string, TcpClient> clients = new();
private static Action<byte[], int?, string>? onReceive = null;
private static ServerStatus status = ServerStatus.Pending;
public static ServerStatus Status
{
get => status;
set
{
status = value;
}
}
private static void Init()
{
disposed = false;
clients.Clear();
var port = ConfigManager.AppConfig.Web.UserSpecifiedPluginsServerPort;
if (port < 0 || port > 65535) port = null;
listener = new(IPAddress.Any, port ?? 0);
keepListen = true;
}
/// <summary>
/// 接收客户端
/// </summary>
private static void AcceptClient()
{
var location = $"{nameof(PluginsServer)}.{nameof(AcceptClient)}";
try
{
while (keepListen && listener is not null)
{
if (listener.Pending())
{
var client = listener.AcceptTcpClient();
if (client.Client.RemoteEndPoint is not IPEndPoint endpoint) continue;
clients.Add(endpoint.ToString(), client);
Log.Information($"New plugin connection: {endpoint}");
ReceiveMessage(client);
}
}
}
catch (Exception ex)
{
Log.Error(ex, $"In {location}: {ex.Message}");
Status = ServerStatus.Errored;
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="client">TcpClient</param>
private static void ReceiveMessage(TcpClient client)
{
var location = $"{nameof(PluginsServer)}.{nameof(ReceiveMessage)}";
IPEndPoint? endpoint = null;
NetworkStream? stream = null;
new Thread(async () =>
{
try
{
endpoint = client.Client.RemoteEndPoint as IPEndPoint;
stream = client.GetStream();
if (endpoint is null || stream is null) return;
while (keepListen)
{
var buffer = new byte[ConfigManager.AppConfig.Web.SocketBufferSize];
var length = stream is null ? 0 : await stream.ReadAsync(buffer);
if (length > 0)
{
onReceive?.Invoke(buffer, length, endpoint.ToString());
var msg = buffer.ToUTF8(0, length);
Log.Information($"From: {endpoint}\tReceive: {msg}");
if (msg.StartsWith("PluginStruct: "))
{
PluginsNetwork.Execute(msg[14..], endpoint);
var workPath = ConfigManager.AppConfig.App.LocalPluginsDataFolder.GetFullPath();
var sendtxt = $"WorkPath: {workPath}";
var bytes = sendtxt.FromUTF8();
stream?.Write(bytes, 0, bytes.Length);
}
//发送到其他客户端
//foreach (KeyValuePair<string, TcpClient> kvp in clients)
//{
// if (kvp.Value != client)
// {
// byte[] writeData = Encoding.UTF8.GetBytes(msg);
// NetworkStream writeStream = kvp.Value.GetStream();
// writeStream.Write(writeData, 0, writeData.Length);
// }
//}
}
else break; //客户端断开连接 跳出循环
}
}
catch (Exception ex)
{
Log.Error(ex, $"In {location}: {ex.Message}");
Log.Information($"Connection broke from: {endpoint}");
Status = ServerStatus.Errored;
}
finally
{
if (endpoint is not null)
{
PluginsNetwork.Disconnect(endpoint);
clients.Remove(endpoint.ToString());
}
stream?.CloseAndDispose();
client.CloseAndDispose();
}
}).Start();
}
public async Task<PluginsServer> Broadcast(byte[] content)
{
await Task.Run(() =>
{
//TODO: 向所有插件广播内容的方法
});
return this;
}
public async Task<PluginsServer> BroadCast(byte[] content, Func<TcpClient, bool>? pattern)
{
await Task.Run(() =>
{
//TODO: 向符合条件的插件广播内容的方法
});
return this;
}
public async Task<PluginsServer> Send(byte[] content, string target)
{
await Task.Run(() =>
{
//TODO: 向指定插件发送内容的方法
});
return this;
}
public PluginsServer OnReceive(Action<byte[], int?, string> action)
{
onReceive = action;
return this;
}
public async Task<PluginsServer> Start()
{
var location = $"{nameof(PluginsServer)}.{nameof(Start)}";
await TasksManager.RunTaskAsync(() =>
{
Status = ServerStatus.Starting;
Init();
if (listener is null) return;
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port; // 取服务端口号
GlobalInfo.PluginServerPort = port; // 全局端口号标明
EventService.Invoke(nameof(EventService.PluginsServerPortChanged));
Log.Information($"PluginsServer Port: {port}");
new Thread(AcceptClient).Start();
Status = ServerStatus.Running;
}, location);
return this;
}
public async Task<PluginsServer> Stop()
{
var location = $"{nameof(PluginsServer)}.{nameof(Stop)}";
Status = ServerStatus.Stopping;
keepListen = false;
await TasksManager.RunTaskAsync(() =>
{
foreach (KeyValuePair<string, TcpClient> item in clients)
{
item.Value.Close();
item.Value.Dispose();
}
clients.Clear();
listener?.Stop();
Status = ServerStatus.Pending;
}, location, catchException: true);
return this;
}
public async Task<PluginsServer> Restart()
{
var location = $"{nameof(PluginsServer)}.{nameof(Restart)}";
await TasksManager.RunTaskAsync(async () =>
{
await Stop();
await Start();
}, location);
return this;
}
public void Dispose()
{
if (disposed) return;
disposed = true;
listener = null;
GC.SuppressFinalize(this);
}
}