NetworkXBase.cs
28.4 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HslCommunication.Core.IMessage;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using HslCommunication.BasicFramework;
using HslCommunication.Enthernet;
namespace HslCommunication.Core.Net
{
/// <summary>
/// 包含了主动异步接收的方法实现和文件类异步读写的实现
/// </summary>
public class NetworkXBase : NetworkBase
{
#region Constractor
/// <summary>
/// 默认的无参构造方法
/// </summary>
public NetworkXBase()
{
}
#endregion
#region Protect Member
#endregion
#region Send Bytes Async
/// <summary>
/// 发送数据的方法
/// </summary>
/// <param name="session">通信用的核心对象</param>
/// <param name="content">完整的字节信息</param>
internal void SendBytesAsync( AppSession session, byte[] content )
{
if (content == null) return;
try
{
// 进入发送数据的锁,然后开启异步的数据发送
session.HybirdLockSend.Enter( );
// 启用另外一个网络封装对象进行发送数据
AsyncStateSend state = new AsyncStateSend( )
{
WorkSocket = session.WorkSocket,
Content = content,
AlreadySendLength = 0,
HybirdLockSend = session.HybirdLockSend,
};
state.WorkSocket.BeginSend(
state.Content,
state.AlreadySendLength,
state.Content.Length - state.AlreadySendLength,
SocketFlags.None,
new AsyncCallback( SendCallBack ),
state );
}
catch (ObjectDisposedException)
{
// 不操作
session.HybirdLockSend.Leave( );
}
catch (Exception ex)
{
session.HybirdLockSend.Leave( );
if (!ex.Message.Contains( StringResources.Language.SocketRemoteCloseException ))
{
LogNet?.WriteException( ToString( ), StringResources.Language.SocketSendException, ex );
}
}
}
/// <summary>
/// 发送回发方法
/// </summary>
/// <param name="ar">异步对象</param>
internal void SendCallBack( IAsyncResult ar )
{
if (ar.AsyncState is AsyncStateSend stateone)
{
try
{
stateone.AlreadySendLength += stateone.WorkSocket.EndSend( ar );
if (stateone.AlreadySendLength < stateone.Content.Length)
{
// 继续发送
stateone.WorkSocket.BeginSend( stateone.Content,
stateone.AlreadySendLength,
stateone.Content.Length - stateone.AlreadySendLength,
SocketFlags.None,
new AsyncCallback( SendCallBack ),
stateone );
}
else
{
stateone.HybirdLockSend.Leave( );
// 发送完成
stateone = null;
}
}
catch (ObjectDisposedException)
{
stateone.HybirdLockSend.Leave( );
// 不处理
stateone = null;
}
catch (Exception ex)
{
LogNet?.WriteException( ToString( ), StringResources.Language.SocketEndSendException, ex );
stateone.HybirdLockSend.Leave( );
stateone = null;
}
}
}
#endregion
#region Receive Bytes Async
/// <summary>
/// 重新开始接收下一次的数据传递
/// </summary>
/// <param name="session">网络状态</param>
/// <param name="isProcess">是否触发数据处理</param>
internal void ReBeginReceiveHead( AppSession session, bool isProcess )
{
try
{
byte[] head = session.BytesHead, Content = session.BytesContent;
session.Clear( );
session.WorkSocket.BeginReceive( session.BytesHead, session.AlreadyReceivedHead, session.BytesHead.Length - session.AlreadyReceivedHead,
SocketFlags.None, new AsyncCallback( HeadBytesReceiveCallback ), session );
// 检测是否需要数据处理
if (isProcess)
{
// 校验令牌
if (CheckRemoteToken( head ))
{
Content = HslProtocol.CommandAnalysis( head, Content );
int protocol = BitConverter.ToInt32( head, 0 );
int customer = BitConverter.ToInt32( head, 4 );
// 转移到数据中心处理
DataProcessingCenter( session, protocol, customer, Content );
}
else
{
// 应该关闭网络通信
LogNet?.WriteWarn( ToString( ), StringResources.Language.TokenCheckFailed );
AppSessionRemoteClose( session );
}
}
}
catch (Exception ex)
{
SocketReceiveException( session, ex );
LogNet?.WriteException( ToString( ), ex );
}
}
/// <summary>
/// 指令头接收方法
/// </summary>
/// <param name="ar">异步状态信息</param>
protected void HeadBytesReceiveCallback( IAsyncResult ar )
{
if (ar.AsyncState is AppSession session)
{
try
{
int receiveCount = session.WorkSocket.EndReceive( ar );
if (receiveCount == 0)
{
// 断开了连接,需要做个处理,一个是直接关闭,另一个是触发下线
AppSessionRemoteClose( session );
return;
}
else
{
session.AlreadyReceivedHead += receiveCount;
}
}
catch (ObjectDisposedException)
{
// 不需要处理,来自服务器主动关闭
return;
}
catch (SocketException ex)
{
// 已经断开连接了
SocketReceiveException( session, ex );
LogNet?.WriteException( ToString( ), ex );
return;
}
catch (Exception ex)
{
// 其他乱七八糟的异常重新启用接收数据
ReBeginReceiveHead( session, false );
LogNet?.WriteException( ToString( ), StringResources.Language.SocketEndReceiveException, ex );
return;
}
if (session.AlreadyReceivedHead < session.BytesHead.Length)
{
try
{
// 仍需要接收
session.WorkSocket.BeginReceive( session.BytesHead, session.AlreadyReceivedHead, session.BytesHead.Length - session.AlreadyReceivedHead,
SocketFlags.None, new AsyncCallback( HeadBytesReceiveCallback ), session );
}
catch (Exception ex)
{
SocketReceiveException( session, ex );
LogNet?.WriteException( ToString( ), ex );
}
}
else
{
// 接收完毕,校验令牌
if (!CheckRemoteToken( session.BytesHead ))
{
LogNet?.WriteWarn( ToString( ), StringResources.Language.TokenCheckFailed );
AppSessionRemoteClose( session );
return;
}
int receive_length = BitConverter.ToInt32( session.BytesHead, session.BytesHead.Length - 4 );
session.BytesContent = new byte[receive_length];
if (receive_length > 0)
{
try
{
int receiveSize = session.BytesContent.Length - session.AlreadyReceivedContent;
session.WorkSocket.BeginReceive( session.BytesContent, session.AlreadyReceivedContent, receiveSize,
SocketFlags.None, new AsyncCallback( ContentReceiveCallback ), session );
}
catch (Exception ex)
{
SocketReceiveException( session, ex );
LogNet?.WriteException( ToString( ), ex );
}
}
else
{
// 处理数据并重新启动接收
ReBeginReceiveHead( session, true );
}
}
}
}
/// <summary>
/// 数据内容接收方法
/// </summary>
/// <param name="ar"></param>
private void ContentReceiveCallback( IAsyncResult ar )
{
if (ar.AsyncState is AppSession receive)
{
try
{
receive.AlreadyReceivedContent += receive.WorkSocket.EndReceive( ar );
}
catch (ObjectDisposedException)
{
//不需要处理
return;
}
catch (SocketException ex)
{
//已经断开连接了
SocketReceiveException( receive, ex );
LogNet?.WriteException( ToString( ), ex );
return;
}
catch (Exception ex)
{
//其他乱七八糟的异常重新启用接收数据
ReBeginReceiveHead( receive, false );
LogNet?.WriteException( ToString( ), StringResources.Language.SocketEndReceiveException, ex );
return;
}
if (receive.AlreadyReceivedContent < receive.BytesContent.Length)
{
int receiveSize = receive.BytesContent.Length - receive.AlreadyReceivedContent;
try
{
//仍需要接收
receive.WorkSocket.BeginReceive( receive.BytesContent, receive.AlreadyReceivedContent, receiveSize, SocketFlags.None, new AsyncCallback( ContentReceiveCallback ), receive );
}
catch (Exception ex)
{
ReBeginReceiveHead( receive, false );
LogNet?.WriteException( ToString( ), StringResources.Language.SocketEndReceiveException, ex );
}
}
else
{
//处理数据并重新启动接收
ReBeginReceiveHead( receive, true );
}
}
}
#endregion
#region Special Bytes Send
/// <summary>
/// [自校验] 将文件数据发送至套接字,如果结果异常,则结束通讯
/// </summary>
/// <param name="socket">网络套接字</param>
/// <param name="filename">完整的文件路径</param>
/// <param name="filelength">文件的长度</param>
/// <param name="report">进度报告器</param>
/// <returns>是否发送成功</returns>
protected OperateResult SendFileStreamToSocket( Socket socket, string filename, long filelength, Action<long, long> report = null )
{
try
{
OperateResult result = null;
using (FileStream fs = new FileStream( filename, FileMode.Open, FileAccess.Read ))
{
result = SendStream( socket, fs, filelength, report, true );
}
return result;
}
catch (Exception ex)
{
socket?.Close( );
LogNet?.WriteException( ToString( ), ex );
return new OperateResult( ex.Message );
}
}
/// <summary>
/// [自校验] 将文件数据发送至套接字,具体发送细节将在继承类中实现,如果结果异常,则结束通讯
/// </summary>
/// <param name="socket">套接字</param>
/// <param name="filename">文件名称,文件必须存在</param>
/// <param name="servername">远程端的文件名称</param>
/// <param name="filetag">文件的额外标签</param>
/// <param name="fileupload">文件的上传人</param>
/// <param name="sendReport">发送进度报告</param>
/// <returns>是否发送成功</returns>
protected OperateResult SendFileAndCheckReceive(
Socket socket,
string filename,
string servername,
string filetag,
string fileupload,
Action<long, long> sendReport = null
)
{
// 发送文件名,大小,标签
FileInfo info = new FileInfo( filename );
if (!File.Exists( filename ))
{
// 如果文件不存在
OperateResult stringResult = SendStringAndCheckReceive( socket, 0, "" );
if (!stringResult.IsSuccess) return stringResult;
socket?.Close( );
return new OperateResult( StringResources.Language.FileNotExist );
}
// 文件存在的情况
Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject
{
{ "FileName", new Newtonsoft.Json.Linq.JValue(servername) },
{ "FileSize", new Newtonsoft.Json.Linq.JValue(info.Length) },
{ "FileTag", new Newtonsoft.Json.Linq.JValue(filetag) },
{ "FileUpload", new Newtonsoft.Json.Linq.JValue(fileupload) }
};
// 先发送文件的信息到对方
OperateResult sendResult = SendStringAndCheckReceive( socket, 1, json.ToString( ) );
if (!sendResult.IsSuccess) return sendResult;
// 最后发送
return SendFileStreamToSocket( socket, filename, info.Length, sendReport );
}
/// <summary>
/// [自校验] 将流数据发送至套接字,具体发送细节将在继承类中实现,如果结果异常,则结束通讯
/// </summary>
/// <param name="socket">套接字</param>
/// <param name="stream">文件名称,文件必须存在</param>
/// <param name="servername">远程端的文件名称</param>
/// <param name="filetag">文件的额外标签</param>
/// <param name="fileupload">文件的上传人</param>
/// <param name="sendReport">发送进度报告</param>
/// <returns>是否成功的结果对象</returns>
protected OperateResult SendFileAndCheckReceive(
Socket socket,
Stream stream,
string servername,
string filetag,
string fileupload,
Action<long, long> sendReport = null
)
{
// 文件存在的情况
Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject
{
{ "FileName", new Newtonsoft.Json.Linq.JValue(servername) },
{ "FileSize", new Newtonsoft.Json.Linq.JValue(stream.Length) },
{ "FileTag", new Newtonsoft.Json.Linq.JValue(filetag) },
{ "FileUpload", new Newtonsoft.Json.Linq.JValue(fileupload) }
};
// 发送文件信息
OperateResult fileResult = SendStringAndCheckReceive( socket, 1, json.ToString( ) );
if (!fileResult.IsSuccess) return fileResult;
return SendStream( socket, stream, stream.Length, sendReport, true );
}
#endregion
#region Special Bytes Receive
/// <summary>
/// [自校验] 从套接字中接收文件头信息
/// </summary>
/// <param name="socket">套接字的网络</param>
/// <returns>包含文件信息的结果对象</returns>
protected OperateResult<FileBaseInfo> ReceiveFileHeadFromSocket( Socket socket )
{
// 先接收文件头信息
OperateResult<int, string> receiveString = ReceiveStringContentFromSocket( socket );
if (!receiveString.IsSuccess) return OperateResult.CreateFailedResult<FileBaseInfo>( receiveString );
// 判断文件是否存在
if (receiveString.Content1 == 0)
{
socket?.Close( );
LogNet?.WriteWarn( ToString( ), StringResources.Language.FileRemoteNotExist );
return new OperateResult<FileBaseInfo>( StringResources.Language.FileNotExist );
}
OperateResult<FileBaseInfo> result = new OperateResult<FileBaseInfo>
{
Content = new FileBaseInfo( )
};
try
{
// 提取信息
Newtonsoft.Json.Linq.JObject json = Newtonsoft.Json.Linq.JObject.Parse( receiveString.Content2 );
result.Content.Name = SoftBasic.GetValueFromJsonObject( json, "FileName", "" );
result.Content.Size = SoftBasic.GetValueFromJsonObject( json, "FileSize", 0L );
result.Content.Tag = SoftBasic.GetValueFromJsonObject( json, "FileTag", "" );
result.Content.Upload = SoftBasic.GetValueFromJsonObject( json, "FileUpload", "" );
result.IsSuccess = true;
}
catch (Exception ex)
{
socket?.Close( );
result.Message = "Extra," + ex.Message;
}
return result;
}
/// <summary>
/// [自校验] 从网络中接收一个文件,如果结果异常,则结束通讯
/// </summary>
/// <param name="socket">网络套接字</param>
/// <param name="savename">接收文件后保存的文件名</param>
/// <param name="receiveReport">接收进度报告</param>
/// <returns>包含文件信息的结果对象</returns>
protected OperateResult<FileBaseInfo> ReceiveFileFromSocket( Socket socket, string savename, Action<long, long> receiveReport )
{
// 先接收文件头信息
OperateResult<FileBaseInfo> fileResult = ReceiveFileHeadFromSocket( socket );
if (!fileResult.IsSuccess) return fileResult;
try
{
OperateResult write = null;
using (FileStream fs = new FileStream( savename, FileMode.Create, FileAccess.Write ))
{
write = WriteStream( socket, fs, fileResult.Content.Size, receiveReport, true );
}
if (!write.IsSuccess)
{
if (File.Exists( savename )) File.Delete( savename );
return OperateResult.CreateFailedResult<FileBaseInfo>( write );
}
return fileResult;
}
catch (Exception ex)
{
LogNet?.WriteException( ToString( ), ex );
socket?.Close( );
return new OperateResult<FileBaseInfo>( )
{
Message = ex.Message
};
}
}
/// <summary>
/// [自校验] 从网络中接收一个文件,写入数据流,如果结果异常,则结束通讯,参数顺序文件名,文件大小,文件标识,上传人
/// </summary>
/// <param name="socket">网络套接字</param>
/// <param name="stream">等待写入的数据流</param>
/// <param name="receiveReport">接收进度报告</param>
/// <returns></returns>
protected OperateResult<FileBaseInfo> ReceiveFileFromSocket( Socket socket, Stream stream, Action<long, long> receiveReport )
{
// 先接收文件头信息
OperateResult<FileBaseInfo> fileResult = ReceiveFileHeadFromSocket( socket );
if (!fileResult.IsSuccess) return fileResult;
try
{
WriteStream( socket, stream, fileResult.Content.Size, receiveReport, true );
return fileResult;
}
catch (Exception ex)
{
LogNet?.WriteException( ToString( ), ex );
socket?.Close( );
return new OperateResult<FileBaseInfo>( )
{
Message = ex.Message
};
}
}
#endregion
#region File Operate
/// <summary>
/// 删除文件的操作
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
protected bool DeleteFileByName( string filename )
{
try
{
if (!File.Exists( filename )) return true;
File.Delete( filename );
return true;
}
catch (Exception ex)
{
LogNet?.WriteException( ToString( ), "delete file failed:" + filename, ex );
return false;
}
}
/// <summary>
/// 预处理文件夹的名称,除去文件夹名称最后一个'\',如果有的话
/// </summary>
/// <param name="folder">文件夹名称</param>
/// <returns></returns>
protected string PreprocessFolderName( string folder )
{
if (folder.EndsWith( @"\" ))
{
return folder.Substring( 0, folder.Length - 1 );
}
else
{
return folder;
}
}
#endregion
#region Virtual Method
/// <summary>
/// 数据处理中心,应该继承重写
/// </summary>
/// <param name="session">连接状态</param>
/// <param name="protocol">协议头</param>
/// <param name="customer">用户自定义</param>
/// <param name="content">数据内容</param>
internal virtual void DataProcessingCenter( AppSession session, int protocol, int customer, byte[] content )
{
}
/// <summary>
/// 接收出错的时候进行处理
/// </summary>
/// <param name="session">会话内容</param>
/// <param name="ex">异常信息</param>
internal virtual void SocketReceiveException( AppSession session, Exception ex )
{
}
/// <summary>
/// 当远端的客户端关闭连接时触发
/// </summary>
/// <param name="session">会话信息</param>
internal virtual void AppSessionRemoteClose( AppSession session )
{
}
#endregion
#region StreamWriteRead
/// <summary>
/// 发送一个流的所有数据到网络套接字
/// </summary>
/// <param name="socket">套接字</param>
/// <param name="stream">内存流</param>
/// <param name="receive">发送的数据长度</param>
/// <param name="report">进度报告的委托</param>
/// <param name="reportByPercent">进度报告是否按照百分比报告</param>
/// <returns>是否成功的结果对象</returns>
protected OperateResult SendStream( Socket socket, Stream stream, long receive, Action<long, long> report, bool reportByPercent )
{
byte[] buffer = new byte[102400]; // 100K的数据缓存池
long SendTotal = 0;
long percent = 0;
stream.Position = 0;
while (SendTotal < receive)
{
// 先从流中接收数据
OperateResult<int> read = ReadStream( stream, buffer );
if (!read.IsSuccess) return new OperateResult( )
{
Message = read.Message,
};
else
{
SendTotal += read.Content;
}
// 然后再异步写到socket中
byte[] newBuffer = new byte[read.Content];
Array.Copy( buffer, 0, newBuffer, 0, newBuffer.Length );
OperateResult write = SendBytesAndCheckReceive( socket, read.Content, newBuffer );
if (!write.IsSuccess)
{
return new OperateResult( )
{
Message = write.Message,
};
}
// 报告进度
if (reportByPercent)
{
long percentCurrent = SendTotal * 100 / receive;
if (percent != percentCurrent)
{
percent = percentCurrent;
report?.Invoke( SendTotal, receive );
}
}
else
{
// 报告进度
report?.Invoke( SendTotal, receive );
}
}
return OperateResult.CreateSuccessResult( );
}
/// <summary>
/// 从套接字中接收所有的数据然后写入到流当中去
/// </summary>
/// <param name="socket">套接字</param>
/// <param name="stream">数据流</param>
/// <param name="totalLength">所有数据的长度</param>
/// <param name="report">进度报告</param>
/// <param name="reportByPercent">进度报告是否按照百分比</param>
/// <returns>是否成功的结果对象</returns>
protected OperateResult WriteStream( Socket socket, Stream stream, long totalLength, Action<long, long> report, bool reportByPercent )
{
long count_receive = 0;
long percent = 0;
while (count_receive < totalLength)
{
// 先从流中异步接收数据
OperateResult<int,byte[]> read = ReceiveBytesContentFromSocket( socket );
if (!read.IsSuccess)
{
return new OperateResult( )
{
Message = read.Message,
};
}
count_receive += read.Content1;
// 开始写入文件流
OperateResult write = WriteStream( stream, read.Content2 );
if (!write.IsSuccess)
{
return new OperateResult( )
{
Message = write.Message,
};
}
// 报告进度
if (reportByPercent)
{
long percentCurrent = count_receive * 100 / totalLength;
if (percent != percentCurrent)
{
percent = percentCurrent;
report?.Invoke( count_receive, totalLength );
}
}
else
{
report?.Invoke( count_receive, totalLength );
}
}
return OperateResult.CreateSuccessResult( );
}
#endregion
#region Object Override
/// <summary>
/// 获取本对象的字符串表示形式
/// </summary>
/// <returns>字符串信息</returns>
public override string ToString()
{
return "NetworkXBase";
}
#endregion
}
}