schangxiang@126.com
2025-11-04 ca398287db3f5ea01f03aac4a85edb13b28100a6
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace Sodao.FastSocket.SocketBase
{
    /// <summary>
    /// base host
    /// </summary>
    public abstract class BaseHost : IHost
    {
        #region Members
        private static long s_connectionID = 1000L;
        private long m_connectionID;
        private readonly ConnectionCollection _listConnections = new ConnectionCollection();
        private readonly SocketAsyncEventArgsPool _saePool = null;
        #endregion
 
        #region Constructors
        /// <summary>
        /// new
        /// </summary>
        /// <param name="socketBufferSize"></param>
        /// <param name="messageBufferSize"></param>
        /// <exception cref="ArgumentOutOfRangeException">socketBufferSize</exception>
        /// <exception cref="ArgumentOutOfRangeException">messageBufferSize</exception>
        protected BaseHost(int socketBufferSize, int messageBufferSize)
        {
            if (socketBufferSize < 1) throw new ArgumentOutOfRangeException("socketBufferSize");
            if (messageBufferSize < 1) throw new ArgumentOutOfRangeException("messageBufferSize");
 
            this.SocketBufferSize = socketBufferSize;
            this.MessageBufferSize = messageBufferSize;
            this._saePool = new SocketAsyncEventArgsPool(messageBufferSize);
        }
        #endregion
 
        #region IHost Members
        /// <summary>
        /// get socket buffer size
        /// </summary>
        public int SocketBufferSize
        {
            get;
            private set;
        }
        /// <summary>
        /// get message buffer size
        /// </summary>
        public int MessageBufferSize
        {
            get;
            private set;
        }
 
        /// <summary>
        /// create new <see cref="IConnection"/>
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">socket is null</exception>
        public virtual IConnection NewConnection(Socket socket)
        {
            if (socket == null) throw new ArgumentNullException("socket");
 
            socket.NoDelay = true;
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
            socket.ReceiveBufferSize = this.SocketBufferSize;
            socket.SendBufferSize = this.SocketBufferSize;
            return new DefaultConnection(this.NextConnectionID(), socket, this);
        }
        /// <summary>
        /// get <see cref="IConnection"/> by connectionID
        /// </summary>
        /// <param name="connectionID"></param>
        /// <returns></returns>
        public IConnection GetConnectionByID(long connectionID)
        {
            return this._listConnections.Get(connectionID);
        }
        /// <summary>
        /// list all <see cref="IConnection"/>
        /// </summary>
        /// <returns></returns>
        public IConnection[] ListAllConnection()
        {
            return this._listConnections.ToArray();
        }
        /// <summary>
        /// get connection count.
        /// </summary>
        /// <returns></returns>
        public int CountConnection()
        {
            return this._listConnections.Count();
        }
 
        /// <summary>
        /// 启动
        /// </summary>
        public virtual void Start()
        {
        }
        /// <summary>
        /// 停止
        /// </summary>
        public virtual void Stop()
        {
            this._listConnections.DisconnectAll();
        }
        #endregion
 
        #region Protected Methods
        /// <summary>
        /// 生成下一个连接ID
        /// </summary>
        /// <returns></returns>
        protected long NextConnectionID()
        {
            this.m_connectionID = Interlocked.Increment(ref BaseHost.s_connectionID);
            return this.m_connectionID;
        }
        /// <summary>
        /// register connection
        /// </summary>
        /// <param name="connection"></param>
        /// <exception cref="ArgumentNullException">connection is null</exception>
        protected void RegisterConnection(IConnection connection)
        {
            if (connection == null) throw new ArgumentNullException("connection");
            if (connection.Active)
            {
                this._listConnections.Add(connection);
                this.OnConnected(connection);
            }
        }
        /// <summary>
        /// OnConnected
        /// </summary>
        /// <param name="connection"></param>
        protected virtual void OnConnected(IConnection connection)
        {
            Log.Trace.Debug(string.Concat("socket connected, id:", connection.ConnectionID.ToString(),
                ", remot endPoint:", connection.RemoteEndPoint == null ? "unknow" : connection.RemoteEndPoint.ToString(),
                ", local endPoint:", connection.LocalEndPoint == null ? "unknow" : connection.LocalEndPoint.ToString()));
        }
        /// <summary>
        /// OnStartSending
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="packet"></param>
        protected virtual void OnStartSending(IConnection connection, Packet packet)
        {
        }
        /// <summary>
        /// OnSendCallback
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="packet"></param>
        /// <param name="isSuccess"></param>
        protected virtual void OnSendCallback(IConnection connection, Packet packet, bool isSuccess)
        {
        }
        /// <summary>
        /// OnMessageReceived
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="e"></param>
        protected virtual void OnMessageReceived(IConnection connection, MessageReceivedEventArgs e)
        {
        }
        /// <summary>
        /// OnDisconnected
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="ex"></param>
        /// <exception cref="ArgumentNullException">connection is null</exception>
        protected virtual void OnDisconnected(IConnection connection, Exception ex)
        {
            this._listConnections.Remove(connection.ConnectionID);
            Log.Trace.Debug(string.Concat("socket disconnected, id:", connection.ConnectionID.ToString(),
                ", remot endPoint:", connection.RemoteEndPoint == null ? "unknow" : connection.RemoteEndPoint.ToString(),
                ", local endPoint:", connection.LocalEndPoint == null ? "unknow" : connection.LocalEndPoint.ToString(),
                ex == null ? string.Empty : string.Concat(", reason is: ", ex.ToString())));
        }
        /// <summary>
        /// OnError
        /// </summary>
        /// <param name="connection"></param>
        /// <param name="ex"></param>
        protected virtual void OnConnectionError(IConnection connection, Exception ex)
        {
            Log.Trace.Error(ex.Message, ex);
        }
        #endregion
 
        /// <summary>
        /// <see cref="SocketAsyncEventArgs"/> pool
        /// </summary>
        private class SocketAsyncEventArgsPool
        {
            #region Private Members
            private readonly int _messageBufferSize;
            private readonly ConcurrentStack<SocketAsyncEventArgs> _pool =
                new ConcurrentStack<SocketAsyncEventArgs>();
            #endregion
 
            #region Constructors
            /// <summary>
            /// new
            /// </summary>
            /// <param name="messageBufferSize"></param>
            public SocketAsyncEventArgsPool(int messageBufferSize)
            {
                this._messageBufferSize = messageBufferSize;
            }
            #endregion
 
            #region Public Methods
            /// <summary>
            /// acquire
            /// </summary>
            /// <returns></returns>
            public SocketAsyncEventArgs Acquire()
            {
                SocketAsyncEventArgs e = null;
                if (this._pool.TryPop(out e)) return e;
 
                e = new SocketAsyncEventArgs();
                e.SetBuffer(new byte[this._messageBufferSize], 0, this._messageBufferSize);
                return e;
            }
            /// <summary>
            /// release
            /// </summary>
            /// <param name="e"></param>
            public void Release(SocketAsyncEventArgs e)
            {
                if (this._pool.Count < 10000)
                {
                    this._pool.Push(e);
                    return;
                }
 
                e.Dispose();
            }
            #endregion
        }
 
        #region DefaultConnection
        /// <summary>
        /// default socket connection
        /// </summary>
        private class DefaultConnection : IConnection
        {
            #region Private Members
            private int _active = 1;
            private DateTime _latestActiveTime = Utils.Date.UtcNow;
            private readonly int _messageBufferSize;
            private readonly BaseHost _host = null;
 
            private readonly Socket _socket = null;
 
            private SocketAsyncEventArgs _saeSend = null;
            private Packet _currSendingPacket = null;
            private readonly PacketQueue _packetQueue = null;
 
            private SocketAsyncEventArgs _saeReceive = null;
            private MemoryStream _tsStream = null;
            private int _isReceiving = 0;
 
            private DateTime _lastAliveTime;
            #endregion
 
            #region Constructors
            /// <summary>
            /// new
            /// </summary>
            /// <param name="connectionID"></param>
            /// <param name="socket"></param>
            /// <param name="host"></param>
            /// <exception cref="ArgumentNullException">socket is null</exception>
            /// <exception cref="ArgumentNullException">host is null</exception>
            public DefaultConnection(long connectionID, Socket socket, BaseHost host)
            {
                if (socket == null) throw new ArgumentNullException("socket");
                if (host == null) throw new ArgumentNullException("host");
 
                this.ConnectionID = connectionID;
                this._socket = socket;
                this._messageBufferSize = host.MessageBufferSize;
                this._host = host;
                this._lastAliveTime = DateTime.Now;
 
                try
                {
                    this.LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;
                    this.RemoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
                }
                catch (Exception ex) { Log.Trace.Error("get socket endPoint error.", ex); }
 
                //init send
                this._saeSend = host._saePool.Acquire();
                this._saeSend.Completed += this.SendAsyncCompleted;
                this._packetQueue = new PacketQueue(this.SendPacketInternal);
 
                //init receive
                this._saeReceive = host._saePool.Acquire();
                this._saeReceive.Completed += this.ReceiveAsyncCompleted;
            }
            #endregion
 
            #region IConnection Members
            /// <summary>
            /// 连接断开事件
            /// </summary>
            public event DisconnectedHandler Disconnected;
 
            /// <summary>
            /// return the connection is active.
            /// </summary>
            public bool Active
            {
                get { return Thread.VolatileRead(ref this._active) == 1; }
            }
            /// <summary>
            /// get the connection latest active time.
            /// </summary>
            public DateTime LatestActiveTime
            {
                get { return this._latestActiveTime; }
            }
            /// <summary>
            /// get the connection id.
            /// </summary>
            public long ConnectionID { get; private set; }
            /// <summary>
            /// 获取本地IP地址
            /// </summary>
            public IPEndPoint LocalEndPoint { get; private set; }
            /// <summary>
            /// 获取远程IP地址
            /// </summary>
            public IPEndPoint RemoteEndPoint { get; private set; }
            /// <summary>
            /// 获取或设置与用户数据
            /// </summary>
            public object UserData { get; set; }
 
            /// <summary>
            /// 异步发送数据
            /// </summary>
            /// <param name="packet"></param>
            public void BeginSend(Packet packet)
            {
                if (!this._packetQueue.TrySend(packet))
                    this.OnSendCallback(packet, false);
            }
            /// <summary>
            /// 异步接收数据
            /// </summary>
            public void BeginReceive()
            {
                if (Interlocked.CompareExchange(ref this._isReceiving, 1, 0) == 0)
                    this.ReceiveInternal();
            }
            /// <summary>
            /// 异步断开连接
            /// </summary>
            /// <param name="ex"></param>
            public void BeginDisconnect(Exception ex = null)
            {
                if (Interlocked.CompareExchange(ref this._active, 0, 1) == 1)
                    this.DisconnectInternal(ex);
            }
            #endregion
 
            #region Private Methods
 
            #region Free
            /// <summary>
            /// free send queue
            /// </summary>
            private void FreeSendQueue()
            {
                var result = this._packetQueue.Close();
                if (result.BeforeState == PacketQueue.CLOSED) return;
 
                if (result.Packets != null)
                    foreach (var p in result.Packets) this.OnSendCallback(p, false);
 
                if (result.BeforeState == PacketQueue.IDLE) this.FreeSend();
            }
            /// <summary>
            /// free for send.
            /// </summary>
            private void FreeSend()
            {
                this._currSendingPacket = null;
                this._saeSend.Completed -= this.SendAsyncCompleted;
                this._host._saePool.Release(this._saeSend);
                this._saeSend = null;
            }
            /// <summary>
            /// free fo receive.
            /// </summary>
            private void FreeReceive()
            {
                this._saeReceive.Completed -= this.ReceiveAsyncCompleted;
                this._host._saePool.Release(this._saeReceive);
                this._saeReceive = null;
                if (this._tsStream != null)
                {
                    this._tsStream.Close();
                    this._tsStream = null;
                }
            }
            #endregion
 
            #region Fire Events
            /// <summary>
            /// fire StartSending
            /// </summary>
            /// <param name="packet"></param>
            private void OnStartSending(Packet packet)
            {
                this._host.OnStartSending(this, packet);
            }
            /// <summary>
            /// fire SendCallback
            /// </summary>
            /// <param name="packet"></param>
            /// <param name="isSuccess"></param>
            private void OnSendCallback(Packet packet, bool isSuccess)
            {
                if (isSuccess) this._latestActiveTime = Utils.Date.UtcNow;
                else packet.SentSize = 0;
 
                this._host.OnSendCallback(this, packet, isSuccess);
            }
            /// <summary>
            /// fire MessageReceived
            /// </summary>
            /// <param name="e"></param>
            private void OnMessageReceived(MessageReceivedEventArgs e)
            {
                this._latestActiveTime = Utils.Date.UtcNow;
                try
                {
                    this._host.OnMessageReceived(this, e);
                }
                catch { }
            }
            /// <summary>
            /// fire Disconnected
            /// </summary>
            private void OnDisconnected(Exception ex)
            {
                if (this.Disconnected != null) this.Disconnected(this, ex);
                this._host.OnDisconnected(this, ex);
            }
            /// <summary>
            /// fire Error
            /// </summary>
            /// <param name="ex"></param>
            private void OnError(Exception ex)
            {
                this._host.OnConnectionError(this, ex);
            }
            #endregion
 
            #region Send
            /// <summary>
            /// internal send packet.
            /// </summary>
            /// <param name="packet"></param>
            /// <exception cref="ArgumentNullException">packet is null</exception>
            private void SendPacketInternal(Packet packet)
            {
                this._currSendingPacket = packet;
                this.OnStartSending(packet);
                this.SendPacketInternal(this._saeSend);
            }
            /// <summary>
            /// internal send packet.
            /// </summary>
            /// <param name="e"></param>
            private void SendPacketInternal(SocketAsyncEventArgs e)
            {
                var packet = this._currSendingPacket;
 
                //按messageBufferSize大小分块传输
                var length = Math.Min(packet.Payload.Length - packet.SentSize, this._messageBufferSize);
                var completedAsync = true;
                try
                {
                    //copy data to send buffer
                    Buffer.BlockCopy(packet.Payload, packet.SentSize, e.Buffer, 0, length);
                    e.SetBuffer(0, length);
                    completedAsync = this._socket.SendAsync(e);
                }
                catch (Exception ex)
                {
                    this.BeginDisconnect(ex);
                    this.FreeSend();
                    this.OnSendCallback(packet, false);
                    this.OnError(ex);
                }
 
                if (!completedAsync)
                    ThreadPool.QueueUserWorkItem(_ => this.SendAsyncCompleted(this, e));
            }
            /// <summary>
            /// async send callback
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void SendAsyncCompleted(object sender, SocketAsyncEventArgs e)
            {
                var packet = this._currSendingPacket;
 
                //send error!
                if (e.SocketError != SocketError.Success)
                {
                    this.BeginDisconnect(new SocketException((int)e.SocketError));
                    this.FreeSend();
                    this.OnSendCallback(packet, false);
                    return;
                }
 
                packet.SentSize += e.BytesTransferred;
 
                if (e.Offset + e.BytesTransferred < e.Count)
                {
                    //continue to send until all bytes are sent!
                    var completedAsync = true;
                    try
                    {
                        e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred - e.Offset);
                        completedAsync = this._socket.SendAsync(e);
                    }
                    catch (Exception ex)
                    {
                        this.BeginDisconnect(ex);
                        this.FreeSend();
                        this.OnSendCallback(packet, false);
                        this.OnError(ex);
                    }
 
                    if (!completedAsync)
                        ThreadPool.QueueUserWorkItem(_ => this.SendAsyncCompleted(sender, e));
                }
                else
                {
                    if (packet.IsSent())
                    {
                        this._currSendingPacket = null;
                        this.OnSendCallback(packet, true);
 
                        //try send next packet
                        if (!this._packetQueue.TrySendNext()) this.FreeSend();
                    }
                    else this.SendPacketInternal(e);//continue send this packet
                }
            }
            #endregion
 
            #region Receive
            /// <summary>
            /// receive
            /// </summary>
            private void ReceiveInternal()
            {
                bool completed = true;
                try { completed = this._socket.ReceiveAsync(this._saeReceive); }
                catch (Exception ex)
                {
                    this.BeginDisconnect(ex);
                    this.FreeReceive();
                    this.OnError(ex);
                }
 
                if (!completed)
                    ThreadPool.QueueUserWorkItem(_ => this.ReceiveAsyncCompleted(this, this._saeReceive));
            }
            /// <summary>
            /// async receive callback
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void ReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e)
            {
                if (e.SocketError != SocketError.Success)
                {
                    this.BeginDisconnect(new SocketException((int)e.SocketError));
                    this.FreeReceive();
                    return;
                }
 
                if (e.BytesTransferred < 1)
                {
                    this.BeginDisconnect();
                    this.FreeReceive();
                    return;
                }
 
                ArraySegment<byte> buffer;
                var ts = this._tsStream;
                if (ts == null || ts.Length == 0)
                    buffer = new ArraySegment<byte>(e.Buffer, 0, e.BytesTransferred);
                else
                {
                    ts.Write(e.Buffer, 0, e.BytesTransferred);
                    buffer = new ArraySegment<byte>(ts.GetBuffer(), 0, (int)ts.Length);
                }
 
                this.OnMessageReceived(new MessageReceivedEventArgs(buffer, this.MessageProcessCallback));
            }
            /// <summary>
            /// message process callback
            /// </summary>
            /// <param name="payload"></param>
            /// <param name="readlength"></param>
            /// <exception cref="ArgumentOutOfRangeException">readlength less than 0 or greater than payload.Count.</exception>
            private void MessageProcessCallback(ArraySegment<byte> payload, int readlength)
            {
                if (readlength < 0 || readlength > payload.Count)
                    throw new ArgumentOutOfRangeException("readlength", "readlength less than 0 or greater than payload.Count.");
 
                var ts = this._tsStream;
                if (readlength == 0)
                {
                    if (ts == null) this._tsStream = ts = new MemoryStream(this._messageBufferSize);
                    else ts.SetLength(0);
 
                    ts.Write(payload.Array, payload.Offset, payload.Count);
                    this.ReceiveInternal();
                    return;
                }
 
                if (readlength == payload.Count)
                {
                    if (ts != null) ts.SetLength(0);
                    this.ReceiveInternal();
                    return;
                }
 
                //粘包处理
                this.OnMessageReceived(new MessageReceivedEventArgs(
                    new ArraySegment<byte>(payload.Array, payload.Offset + readlength, payload.Count - readlength),
                    this.MessageProcessCallback));
            }
            #endregion
 
            #region Disconnect
            /// <summary>
            /// disconnect
            /// </summary>
            /// <param name="reason"></param>
            private void DisconnectInternal(Exception reason)
            {
                var e = new SocketAsyncEventArgs();
                e.Completed += this.DisconnectAsyncCompleted;
                e.UserToken = reason;
 
                var completedAsync = true;
                try
                {
                    this._socket.Shutdown(SocketShutdown.Both);
                    completedAsync = this._socket.DisconnectAsync(e);
                }
                catch (Exception ex)
                {
                    Log.Trace.Error(ex.Message, ex);
                    ThreadPool.QueueUserWorkItem(_ => this.DisconnectAsyncCompleted(this, e));
                    return;
                }
 
                if (!completedAsync)
                    ThreadPool.QueueUserWorkItem(_ => this.DisconnectAsyncCompleted(this, e));
            }
            /// <summary>
            /// async disconnect callback
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void DisconnectAsyncCompleted(object sender, SocketAsyncEventArgs e)
            {
                //dispose socket
                try { this._socket.Close(); }
                catch (Exception ex) { Log.Trace.Error(ex.Message, ex); }
 
                //dispose socketAsyncEventArgs
                var reason = e.UserToken as Exception;
                e.Completed -= this.DisconnectAsyncCompleted;
                e.Dispose();
 
                //fire disconnected
                this.OnDisconnected(reason);
                //close send queue
                this.FreeSendQueue();
            }
            #endregion
 
            #endregion
 
            #region PacketQueue
            /// <summary>
            /// packet queue
            /// </summary>
            private class PacketQueue
            {
                #region Private Members
                public const int IDLE = 1;     //空闲状态
                public const int SENDING = 2;  //发送中
                public const int ENQUEUE = 3;  //入列状态
                public const int DEQUEUE = 4;  //出列状态
                public const int CLOSED = 5;   //已关闭
 
                private int _state = IDLE;      //当前状态
                private Queue<Packet> _queue = new Queue<Packet>();
                private Action<Packet> _sendAction = null;
                #endregion
 
                #region Constructors
                /// <summary>
                /// new
                /// </summary>
                /// <param name="sendAction"></param>
                /// <exception cref="ArgumentNullException">sendAction is null.</exception>
                public PacketQueue(Action<Packet> sendAction)
                {
                    if (sendAction == null) throw new ArgumentNullException("sendAction");
                    this._sendAction = sendAction;
                }
                #endregion
 
                #region Public Methods
                /// <summary>
                /// try send packet
                /// </summary>
                /// <param name="packet"></param>
                /// <returns>if CLOSED return false.</returns>
                public bool TrySend(Packet packet)
                {
                    var spin = true;
                    while (spin)
                    {
                        switch (this._state)
                        {
                            case IDLE:
                                if (Interlocked.CompareExchange(ref this._state, SENDING, IDLE) == IDLE)
                                    spin = false;
                                break;
                            case SENDING:
                                if (Interlocked.CompareExchange(ref this._state, ENQUEUE, SENDING) == SENDING)
                                {
                                    this._queue.Enqueue(packet);
                                    this._state = SENDING;
                                    return true;
                                }
                                break;
                            case ENQUEUE:
                            case DEQUEUE:
                                Thread.Yield();
                                break;
                            case CLOSED:
                                return false;
                        }
                    }
                    this._sendAction(packet);
                    return true;
                }
                /// <summary>
                /// close
                /// </summary>
                /// <returns></returns>
                public CloseResult Close()
                {
                    var spin = true;
                    int beforeState = -1;
                    while (spin)
                    {
                        switch (this._state)
                        {
                            case IDLE:
                                if (Interlocked.CompareExchange(ref this._state, CLOSED, IDLE) == IDLE)
                                {
                                    spin = false;
                                    beforeState = IDLE;
                                }
                                break;
                            case SENDING:
                                if (Interlocked.CompareExchange(ref this._state, CLOSED, SENDING) == SENDING)
                                {
                                    spin = false;
                                    beforeState = SENDING;
                                }
                                break;
                            case ENQUEUE:
                            case DEQUEUE:
                                Thread.Yield();
                                break;
                            case CLOSED:
                                return new CloseResult(CLOSED, null);
                        }
                    }
 
                    var arrPackets = this._queue.ToArray();
                    this._queue.Clear();
                    this._queue = null;
                    this._sendAction = null;
                    return new CloseResult(beforeState, arrPackets);
                }
                /// <summary>
                /// try send next packet
                /// </summary>
                /// <returns>if CLOSED return false.</returns>
                public bool TrySendNext()
                {
                    var spin = true;
                    Packet packet = null;
                    while (spin)
                    {
                        switch (this._state)
                        {
                            case SENDING:
                                if (Interlocked.CompareExchange(ref this._state, DEQUEUE, SENDING) == SENDING)
                                {
                                    if (this._queue.Count == 0)
                                    {
                                        this._state = IDLE;
                                        return true;
                                    }
 
                                    packet = this._queue.Dequeue();
                                    this._state = SENDING;
                                    spin = false;
                                }
                                break;
                            case ENQUEUE:
                                Thread.Yield();
                                break;
                            case CLOSED:
                                return false;
                        }
                    }
                    this._sendAction(packet);
                    return true;
                }
                #endregion
 
                #region CloseResult
                /// <summary>
                /// close queue result
                /// </summary>
                public sealed class CloseResult
                {
                    /// <summary>
                    /// before close state
                    /// </summary>
                    public readonly int BeforeState;
                    /// <summary>
                    /// wait sending packet array
                    /// </summary>
                    public readonly Packet[] Packets;
 
                    /// <summary>
                    /// new
                    /// </summary>
                    /// <param name="beforeState"></param>
                    /// <param name="packets"></param>
                    public CloseResult(int beforeState, Packet[] packets)
                    {
                        this.BeforeState = beforeState;
                        this.Packets = packets;
                    }
                }
                #endregion
            }
            #endregion
        }
        #endregion
    }
}