NetComplexServer.cs
15.2 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
using HslCommunication.Core;
using HslCommunication.Core.Net;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace HslCommunication.Enthernet
{
/// <summary>
/// 高性能的异步网络服务器类,适合搭建局域网聊天程序,消息推送程序
/// </summary>
/// <remarks>
/// 详细的使用说明,请参照博客<a href="http://www.cnblogs.com/dathlin/p/8097897.html">http://www.cnblogs.com/dathlin/p/8097897.html</a>
/// </remarks>
/// <example>
/// 此处贴上了Demo项目的服务器配置的示例代码
/// <code lang="cs" source="TestProject\ComplexNetServer\FormServer.cs" region="NetComplexServer" title="NetComplexServer示例" />
/// </example>
public class NetComplexServer : NetworkServerBase
{
#region Constructor
/// <summary>
/// 实例化一个网络服务器类对象
/// </summary>
public NetComplexServer()
{
appSessions = new List<AppSession>();
lockSessions = new SimpleHybirdLock();
}
#endregion
#region Private Member
private int connectMaxClient = 1000; // 允许同时登录的最大客户端数量
private List<AppSession> appSessions = null; // 所有客户端连接的对象信息
private SimpleHybirdLock lockSessions = null; // 对象列表操作的锁
#endregion
#region Public Properties
/// <summary>
/// 所支持的同时在线客户端的最大数量,商用限制1000个,最小10个
/// </summary>
public int ConnectMax
{
get { return connectMaxClient; }
set
{
if (value >= 10 && value < 1001)
{
connectMaxClient = value;
}
}
}
/// <summary>
/// 获取或设置服务器是否记录客户端上下线信息
/// </summary>
public bool IsSaveLogClientLineChange { get; set; } = true;
/// <summary>
/// 所有在线客户端的数量
/// </summary>
public int ClientCount => appSessions.Count;
#endregion
#region NetworkServerBase Override
/// <summary>
/// 初始化操作
/// </summary>
protected override void StartInitialization()
{
Thread_heart_check = new Thread(new ThreadStart(ThreadHeartCheck))
{
IsBackground = true,
Priority = ThreadPriority.AboveNormal
};
Thread_heart_check.Start();
base.StartInitialization();
}
/// <summary>
/// 关闭网络时的操作
/// </summary>
protected override void CloseAction()
{
Thread_heart_check?.Abort();
ClientOffline = null;
ClientOnline = null;
AcceptString = null;
AcceptByte = null;
//关闭所有的网络
appSessions.ForEach(m => m.WorkSocket?.Close());
base.CloseAction();
}
/// <summary>
/// 异常下线
/// </summary>
/// <param name="session">会话信息</param>
/// <param name="ex">异常</param>
internal override void SocketReceiveException(AppSession session, Exception ex)
{
if (ex.Message.Contains(StringResources.Language.SocketRemoteCloseException))
{
//异常掉线
TcpStateDownLine(session, false);
}
}
/// <summary>
/// 正常下线
/// </summary>
/// <param name="session">会话信息</param>
internal override void AppSessionRemoteClose(AppSession session)
{
TcpStateDownLine(session, true);
}
#endregion
#region Client Online Offline
private void TcpStateUpLine(AppSession state)
{
lockSessions.Enter();
appSessions.Add(state);
lockSessions.Leave();
// 提示上线
ClientOnline?.Invoke(state);
AllClientsStatusChange?.Invoke(ClientCount);
// 是否保存上线信息
if (IsSaveLogClientLineChange)
{
LogNet?.WriteInfo(ToString(), $"[{state.IpEndPoint}] Name:{ state?.LoginAlias } { StringResources.Language.NetClientOnline }");
}
}
private void TcpStateClose(AppSession state)
{
state?.WorkSocket?.Close();
}
private void TcpStateDownLine(AppSession state, bool is_regular, bool logSave = true)
{
lockSessions.Enter();
bool success = appSessions.Remove(state);
lockSessions.Leave();
if (!success) return;
// 关闭连接
TcpStateClose(state);
// 判断是否正常下线
string str = is_regular ? StringResources.Language.NetClientOffline : StringResources.Language.NetClientBreak;
ClientOffline?.Invoke(state, str);
AllClientsStatusChange?.Invoke(ClientCount);
// 是否保存上线信息
if (IsSaveLogClientLineChange && logSave)
{
LogNet?.WriteInfo(ToString(), $"[{state.IpEndPoint}] Name:{ state?.LoginAlias } { str }");
}
}
#endregion
#region Event Handle
/// <summary>
/// 客户端的上下限状态变更时触发,仅作为在线客户端识别
/// </summary>
public event Action<int> AllClientsStatusChange;
/// <summary>
/// 当客户端上线的时候,触发此事件
/// </summary>
public event Action<AppSession> ClientOnline;
/// <summary>
/// 当客户端下线的时候,触发此事件
/// </summary>
public event Action<AppSession, string> ClientOffline;
/// <summary>
/// 当接收到文本数据的时候,触发此事件
/// </summary>
public event Action<AppSession, NetHandle, string> AcceptString;
/// <summary>
/// 当接收到字节数据的时候,触发此事件
/// </summary>
public event Action<AppSession, NetHandle, byte[]> AcceptByte;
#endregion
#region Login Server
/// <summary>
/// 当接收到了新的请求的时候执行的操作
/// </summary>
/// <param name="socket">异步对象</param>
/// <param name="endPoint">终结点</param>
protected override void ThreadPoolLogin(Socket socket, IPEndPoint endPoint)
{
// 判断连接数是否超出规定
if (appSessions.Count > ConnectMax)
{
socket?.Close();
LogNet?.WriteWarn(ToString(), StringResources.Language.NetClientFull);
return;
}
// 接收用户别名并验证令牌
OperateResult result = new OperateResult();
OperateResult<int, string> readResult = ReceiveStringContentFromSocket(socket);
if (!readResult.IsSuccess) return;
// 登录成功
AppSession session = new AppSession()
{
WorkSocket = socket,
LoginAlias = readResult.Content2,
};
try
{
session.IpEndPoint = (IPEndPoint)socket.RemoteEndPoint;
session.IpAddress = ((IPEndPoint)socket.RemoteEndPoint).Address.ToString();
}
catch (Exception ex)
{
LogNet?.WriteException(ToString(), StringResources.Language.GetClientIpaddressFailed, ex);
}
if (readResult.Content1 == 1)
{
// 电脑端客户端
session.ClientType = "Windows";
}
else if (readResult.Content1 == 2)
{
// Android 客户端
session.ClientType = "Android";
}
try
{
session.WorkSocket.BeginReceive(session.BytesHead, session.AlreadyReceivedHead,
session.BytesHead.Length - session.AlreadyReceivedHead, SocketFlags.None,
new AsyncCallback(HeadBytesReceiveCallback), session);
TcpStateUpLine(session);
Thread.Sleep(100);// 留下一些时间进行反应
}
catch (Exception ex)
{
// 登录前已经出错
TcpStateClose(session);
LogNet?.WriteException(ToString(), StringResources.Language.NetClientLoginFailed, ex);
}
}
#endregion
#region SendAsync Support
/// <summary>
/// 服务器端用于数据发送文本的方法
/// </summary>
/// <param name="session">数据发送对象</param>
/// <param name="customer">用户自定义的数据对象,如不需要,赋值为0</param>
/// <param name="str">发送的文本</param>
public void Send(AppSession session, NetHandle customer, string str)
{
SendBytes(session, HslProtocol.CommandBytes(customer, Token, str));
}
/// <summary>
/// 服务器端用于发送字节的方法
/// </summary>
/// <param name="session">数据发送对象</param>
/// <param name="customer">用户自定义的数据对象,如不需要,赋值为0</param>
/// <param name="bytes">实际发送的数据</param>
public void Send(AppSession session, NetHandle customer, byte[] bytes)
{
SendBytes(session, HslProtocol.CommandBytes(customer, Token, bytes));
}
private void SendBytes(AppSession session, byte[] content)
{
SendBytesAsync(session, content);
}
/// <summary>
/// 服务端用于发送所有数据到所有的客户端
/// </summary>
/// <param name="customer">用户自定义的命令头</param>
/// <param name="str">需要传送的实际的数据</param>
public void SendAllClients(NetHandle customer, string str)
{
for (int i = 0; i < appSessions.Count; i++)
{
Send(appSessions[i], customer, str);
}
}
/// <summary>
/// 服务端用于发送所有数据到所有的客户端
/// </summary>
/// <param name="customer">用户自定义的命令头</param>
/// <param name="data">需要群发客户端的字节数据</param>
public void SendAllClients(NetHandle customer, byte[] data)
{
for (int i = 0; i < appSessions.Count; i++)
{
Send(appSessions[i], customer, data);
}
}
/// <summary>
/// 根据客户端设置的别名进行发送消息
/// </summary>
/// <param name="Alias">客户端上线的别名</param>
/// <param name="customer">用户自定义的命令头</param>
/// <param name="str">需要传送的实际的数据</param>
public void SendClientByAlias(string Alias, NetHandle customer, string str)
{
for (int i = 0; i < appSessions.Count; i++)
{
if (appSessions[i].LoginAlias == Alias)
{
Send(appSessions[i], customer, str);
}
}
}
/// <summary>
/// 根据客户端设置的别名进行发送消息
/// </summary>
/// <param name="Alias">客户端上线的别名</param>
/// <param name="customer">用户自定义的命令头</param>
/// <param name="data">需要传送的实际的数据</param>
public void SendClientByAlias(string Alias, NetHandle customer, byte[] data)
{
for (int i = 0; i < appSessions.Count; i++)
{
if (appSessions[i].LoginAlias == Alias)
{
Send(appSessions[i], customer, data);
}
}
}
#endregion
#region DataProcessingCenter
/// <summary>
/// 数据处理中心
/// </summary>
/// <param name="session">会话对象</param>
/// <param name="protocol">消息的代码</param>
/// <param name="customer">用户消息</param>
/// <param name="content">数据内容</param>
internal override void DataProcessingCenter(AppSession session, int protocol, int customer, byte[] content)
{
if (protocol == HslProtocol.ProtocolCheckSecends)
{
BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(content, 8);
SendBytes(session, HslProtocol.CommandBytes(HslProtocol.ProtocolCheckSecends, customer, Token, content));
session.HeartTime = DateTime.Now;
}
else if (protocol == HslProtocol.ProtocolClientQuit)
{
TcpStateDownLine(session, true);
}
else if (protocol == HslProtocol.ProtocolUserBytes)
{
//接收到字节数据
AcceptByte?.Invoke(session, customer, content);
}
else if (protocol == HslProtocol.ProtocolUserString)
{
//接收到文本数据
string str = Encoding.Unicode.GetString(content);
AcceptString?.Invoke(session, customer, str);
}
else
{
// 其他一概不处理
}
}
#endregion
#region Heart Check
private Thread Thread_heart_check { get; set; } = null;
private void ThreadHeartCheck()
{
while (true)
{
Thread.Sleep(2000);
try
{
for (int i = appSessions.Count - 1; i >= 0; i--)
{
if (appSessions[i] == null)
{
appSessions.RemoveAt(i);
continue;
}
if ((DateTime.Now - appSessions[i].HeartTime).TotalSeconds > 1 * 8)//8次没有收到失去联系
{
LogNet?.WriteWarn(ToString(), StringResources.Language.NetHeartCheckTimeout + appSessions[i].IpAddress.ToString());
TcpStateDownLine(appSessions[i], false, false);
continue;
}
}
}
catch (Exception ex)
{
LogNet?.WriteException(ToString(), StringResources.Language.NetHeartCheckFailed, ex);
}
if (!IsStarted) break;
}
}
#endregion
#region Object Override
/// <summary>
/// 获取本对象的字符串表示形式
/// </summary>
/// <returns>字符串</returns>
public override string ToString()
{
return "NetComplexServer";
}
#endregion
}
}